SED Tips

Display Related Tricks:

1) The 1st line (head -1)
sed q 

2) The first 5 lines (head -5)
sed'5 q '
sed'1, 5! d '


3) The last line (tail -1)
sed-n '$ p'
sed '$! d "


4) The last 5 lines (tail -5)
sed-e: a-e '$ q, N, 6, $ D; ba'

5) The 2 last lines (tail -2)
sed '$! N; $! D'

6) Only lines matcha a reason or a regular expression
sed-n '/ pattern / p'
sed '/ regexp /! d'


7) Only lines that matcha not a reason or a regular expression
sed-n '/ pattern /! p'
sed '/ regexp / d'


8) The line preceding a pattern or a regular expression
sed-n '/ pattern / (g; 1! p;) h'

9) The line following a pattern or a regular expression
sed-n '/ regexp / (n, p;)'

Substitution Related Tricks:

10) Substitute "foo" with "bar" on each line
Only the 1st occurrence
sed 's / foo / bar /'

11) For the 3rd case only
sed 's/foo/bar/3'

12) All occurrences
sed 's / foo / bar / g'

13) Just before the last occurrence
sed 's / \ (.* \) foo \ (.* foo \) / \ 1bar \ 2 /'

14) Only the last case
sed 's / \ (.* \) foo / \ 1bar /'

15) Substitute "foo" with "bar" only lines containing "plop"
sed '/ plop / s / foo / bar / g'

16) Substitute "foo" with "bar" except the lines containing "plop"
sed '/ plop /! s / foo / bar / g '

17) Replace "Foo" or "foo" with "bar" on each line
sed 's / [Ff] oo / bar / g'

18) Replace "blue" or "white" or "red" with "green"
sed 's / blue \ | blank \ | red / green / g'

Remove Related Tricks:

Removing spaces and tabs

19) At the beginning of the line
sed 's / ^ [\ t] * / /
sed 's / ^ \ s * / /' # Using the parameter "\ s"

20) At end of line
sed 's / [\ t ]*$//'

21) At the beginning and end of line
sed 's / ^ [\ t ]*//; s / [\ t ]*$//'

Blank Line Related Tricks:

Removing blank lines

22) All empty lines
sed'/^$/ of
sed'/./! of


23) Only those at the top
sed'/./,$! of
sed-nr'/./,$ /(.*)/ s \ 1 / p '# thank you Adrien

24) Only those at end
sed-e: a-e '/ ^ \ n * $ / ($ d N; ba'-e ')'

Regular Intervals Related Tricks:

Eliminate a line at regular intervals

25) All lines pairs
sed'1 ~ 2d '

26) All the odd lines
sed'2 ~ 2d '

27) Every n lines from the line n
sed'3 ~ 2d '# 2 All lines from line 3

Miscellaneous Related Tricks:

Join lines
28) Attach lines 2 by 2
sed '$! N s / \ n / /'

29) Attach the 3 lines by 3
sed '$! N s / \ n //;$! N s / \ n / /;'

30) If a line ends with a backslash (\), add the following line and replace the end of line (\ n) by a space
sed-e: a-e '/ \ \ $ / N s / \ \ \ n / /; ta'

31) If a line begins with an equal sign (=), add it to the previous line and replace the equal sign (=) with a space
sed-e: a-e '$! N s / \ n = / /; ta'-e 'P, D'

No comments:

Post a Comment