Linux Bash Scripting Tutorial
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 SYNTAX | Explanation | Example |
sed -n /Regular_Expression/p' filename | This will print matching lines | |
sed -n s/Regular_Expression/replacement_text' filename | This will replace the pattern matched string with repleacement text | |
sed 'n,md' filename | Deletes line from n to m | |
sed '/Regular Expression/d | This will delete all the lines matching Regular Expression | |
sed '/Regular Expression/!d | This will deletall all lines except the line(s) contaning Regular Expression | |
sed '1,3d' filename > newfile
mv newfile filename
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
sed '/Volleyball/a Gymnastics' olympic-sports.txt
appends text 'Gymnastics' after 'Volleyball'
sed delete Syntax | Explanation | Example |
sed '3d' filename | deletes third line | |
sed '3,$d' filename | deletes from third line to last line $ in the address indicates last line , is called range operator | |
sed '$d' filename | deletes the last line | |
sed '/RE/d' filename | The line(s) containing RE pattern deleted | |
sed '/RE/!d' filename | The line(s) not conating RE patterns deleted | |
sed '4,+5d' filename | This will delete from line 4 to next 5 lines | |
sed '1,5!d' filename | This will keep lines from 1 to 5,deletes all other lines | |
sed '1~3d' filename | This 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 '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
ADS