Linux Command - sed
The Linux command sed is used for transforming and filtering text. It stands for stream editor.
Using sed is a quick way to swap values in a file. It is also commonly used with piped commands.
Swap the first occurance of ‘abc’ with ‘xyz’ in a file and print out the file:
sed 's/abc/xyz/' test.txt
Swap every occurance of ‘abc’ with ‘xyz’ in a file and print out the file ( g for global ):
sed 's/abc/xyz/g' test.txt
Same but case insensitive:
sed 's/abc/xyz/gI' test.txt
Same but also changes the file:
sed -i 's/abc/xyz/g' test.txt
Create a backup with the specified suffix ( “.bak” ):
sed -i.bak 's/abc/xyz/g' test.txt
Silently update a file without printing it:
sed -in 's/abc/xyz/g' test.txt
Use multiple search and replace patterns in one command:
sed -e 's/abc/123/g' -e 's/xyz/456/g' test.txt
Use extended regex:
sed -E 's/a|b/x/g' test.txt
Use an alternate delimiter:
sed -i 's!abc!xyz!g' test.txt
sed -i 's|abc|xyz|g' test.txt
sed -i 's!https://google.com!https://bing.com!g' test.txt
Do the same thing with piped input:
ps -ef | sed 's/root/abcd/g'
Reuse groups with regex:
sed -E 's/a(bc)/123_&_\1/' test.txt
& | matching portion |
\1 … \9 | matching sub expressions |
Transliterate characters:
sed 'y/abc/123/g' test.txt
If line contains ‘abc’, then replace ‘xyz’ with ‘123’:
sed '/abc/s/xyz/123/g' test.txt
For lines 3-7, swap xyz for 123, global, case insensitive, and duplicate:
sed '3,7 s/xyz/123/gIp'
Append new line with ‘xyz’ on line after matching line:
sed '/abc/axyz'
More examples:
sed '/abc/d' # delete any matching lines
sed '3 d' # delete line 3
sed '3,5 d' # delete lines 3,4,5
sed '3,$ d' # delete from line 3 to end
sed '3 axyz' # append 'xyz' after line 3
sed '/abc/ axyz' # append 'xyz' after any line matching 'abc'
Common options:
-n | for quiet |
-E | extended regular expressions |
-i | edit file in place ( apparently a GNU thing and won’t work on BSD or MacOS ) |
Modifiers for replace:
/g | for global will swap each occurance on each line instead of the first occurance on each line. |
/I | case insensitive |
/p | duplicate matched line |