Linux Bash Scripting Tutorial


SED-Stream Editor

A Stream Editor that takes its commands from a file
Sed is noninteractive stream editor. normally editing files with vi, requires files should be opened, sed is nondescriptive editor. sed makes changes to the file and displays the content on the screen. if u want to save the changed file, then redirect sed output to file. sed often used to find-and-replace actions on lines containg patterns.

sed options:
  • -n --silent --quite
  • -e script add the script to the commands to be executed
  • -f scriptfile add the content of the script file to the commands to be executed
  • -E -r use extended regular expressions in the script
  • -z --null-data seperate lines by null character
  • --version displays sed version information

SED SYNTAXExplanationExample
sed -n /Regular_Expression/p' filenameThis will print matching lines
sed -n s/Regular_Expression/replacement_text' filenameThis will replace the pattern matched string with repleacement text
sed 'n,md' filenameDeletes line from n to m
sed '/Regular Expression/dThis will delete all the lines matching Regular Expression
sed '/Regular Expression/!dThis will deletall all lines except the line(s) contaning Regular Expression

How to modify a file using sed

sed '1,3d' filename > newfile
mv newfile filename

Sed printing with p command

sed '/USA/p'country.txt
all the lines from the file will be printed

sed -n '/USA/p' country.txt
sed -n will print only lines matching Regular Expression

Appending – the a command

sed '/Volleyball/a Gymnastics' olympic-sports.txt
appends text 'Gymnastics' after 'Volleyball'

sed: -e expression #1, char 13: expected \ after `a', `c' or `i'

Inserting – the i command

Changing – the c command

Sed deleting with d command

sed delete SyntaxExplanationExample
sed '3d' filenamedeletes third line
sed '3,$d' filenamedeletes from third line to last line
$ in the address indicates last line
, is called range operator
sed '$d' filenamedeletes the last line
sed '/RE/d' filenameThe line(s) containing RE pattern deleted
sed '/RE/!d' filenameThe line(s) not conating RE patterns deleted
sed '4,+5d' filenameThis will delete from line 4 to next 5 lines
sed '1,5!d' filenameThis will keep lines from 1 to 5,deletes all other lines
sed '1~3d' filenameThis will delete lines 1,4,7,10 and so on... ~ is step increment
sed '2~2d'This will delete every other line starting with line 2 to be deleted.

Sed Substitution with s command

sed 's/Cashew/Almonds/g' shopping.txt

sed 's/[0–9][0–9]$/&.5/' shopping.txt
this will replace 2 digit numbers at the end of the line .5 appended to them

Sed Range of selected lines: the comma

Multiple edits – the e command

Multiple edits – the e command

Reading from files – the r command

Writing to files – the w command

Transform – the y command

Quit – the q command

Holding and getting – the h and g commands

Holding and exchanging – the h and x commands

ADS