KandZ – Tuts

We like to help…!

Linux CLI 46 🐧 sed command

a - sed command and options
sed command(stream editor) is text processing tool.
It can perform basic text transformations on input stream(file or command output)
syntax → sed [options] 'script' inputfile
script → is the script to be executed by sed
common options: -i → Edit files in place (save the changes to the original file)
-e script → Add the script to the list of editing commands. This is typically used when you want to specify multiple scripts.
-f script_file → Read the editing commands from `script_file`.
-n → Suppress automatic printing of pattern space

b - sed common scripts
s/what/with → substitute what with with, s = replace
s/what/with/3 → substitute the 3rd what with with, 3 = 3rd occurence
s/what/with/3h → substitute the 3rd what with with and all others after the 3rd
s/what/with/g → substitute what with with all occurences, g = global
3 s/what/with/ → substitute what with with on line 3, 3 = line 3
n,md → deletes lines from n to m line, d = delete
n a\ newline → appends newline after line n, a=append
/pattern/p → prints lines containing specific pattern

c - sed examples
sed -n '=;p' example.txt prints line numbers
sed 's/This/That/g' example.txt replaces This with That
sed '/This/d' example.txt deletes all This
sed -e 's/This/That/g' -e 's/And/---/' example.txt replace multiple patterns
echo "s/This/That/g" scriptFile create a script file
sed -f scriptFile example.txt use a script file
sed -s 's/This/That/g' example.txt example1.txt replaces This with That in 2 files

Leave a Reply