-
Notifications
You must be signed in to change notification settings - Fork 0
sed
holzkohlengrill edited this page Dec 15, 2023
·
2 revisions
$ cat text
10 tiny toes
this is that
5 funny 0
one two three
tree twice
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'
-
# comment
(until newline) s/<regex>/<replacement>/
-
sed -n 'p;n' text
(skips any other line)
These are normal RegEx'es.
-
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))
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 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
$ seq 9 | sed -n 'p;n;h;n;G;p'
1
3
2
4
6
5
7
9
8
-
p
rint the current line, - get the
n
ext one, -
h
old it, - get the
n
ext one, -
G
et the held line (append it to the pattern space) and -
p
rint that 2-line pattern space with the third and second lines swapped.
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License *.
Code (snippets) are licensed under a MIT License *.
* Unless stated otherwise