Skip to content
holzkohlengrill edited this page Dec 15, 2023 · 2 revisions

Stream editor

$ cat text
10 tiny toes
this is that
5 funny 0
one two three
tree twice

Substitution & basic synthax

sed -i 's/<regexPattern>/<replacewith>/g' text
    ^^  ^                              ^    ^
changes file ("inplace")           "global" |
        |                                   |
   substitute                             input

Comments:

  • Without -i (--in-place) result will be only printed (file stays as it was)
  • sed -i.bak ... changes the file and create a backup file (e.g. text.bak, or any other extension)
  • Without -g only first occurence per line will be changed >> g is a flag
  • Without a imput file user std::in will be used
  • Delimiters: anything which comes after s (substitute as an example) will be used as the delimiter
  • After 's/<regexPattern>/<replacewith>/g' you can concatenate other comands like 's/<regexPattern>/<replacewith>/g;s/<blah>/<blub>/g'

(Basic) Commands

  • # comment (until newline)
  • s/<regex>/<replacement>/
  • sed -n 'p;n' text (skips any other line)

Patterns (2nd position)

These are normal RegEx'es.

Flags (3rd position)

  • g : global (otherwise only first occurence per line)
  • p : print for matches
  • d : delete matching line
  • <number> : replace the s occurence
  • w <filename> : write substitution to a named file
  • q : quit (e.g. sed '6 q' text; go until line 6 and than quit (prints line 1-6))

Lines

sed -i '5!s/<regexPattern>/<replacewith>/g' text

Comments:

  • 5!s...: everything except the 5th line will be substituted
  • 5s...: only the 5th line will be substituted
  • 5,9s...: line 5 to 9 will be substituted

Print lines

Print line 5 to 10:

sed -n '5,10p' text
     ^      ^
     |    print
   silent

In this combination (-n and p) only matches are printed. For ex.:

$ sed -n 's/10/3/gp' text
3 tiny toes

Change line positions

$ seq 9 | sed -n 'p;n;h;n;G;p'
1
3
2
4
6
5
7
9
8
  1. print the current line,
  2. get the next one,
  3. hold it,
  4. get the next one,
  5. Get the held line (append it to the pattern space) and
  6. print that 2-line pattern space with the third and second lines swapped.

Additional Ressources

Clone this wiki locally