Learn to Code via Tutorials on Repl.it!

← Back to all posts
SED S1 : Printing And Deleting Lines with p and d options
sasivanga (13)

Session-1 SED - Stream Editor- Printing And Deleting Lines with p and d options

sed is just command not editor

By using sed command we can retrieve the data present in the file,and even we can edit data of the file

We can perform based on line like delete 2nd line
We can perform operations based context --like word ‘python’ contains

1)Display specific line multiple times :

sed ‘2p’ emp.txt# ⇒ 2nd line will print two times

2)Display only specific line

sed -n '3p' emp.txt
cat emp.txt |head -3 | tail -1 ⇒ regular unix command

3)Display first and last line

sed -n '$p' emp.txt
First line :
sed -n '1p' emp.txt ⇒ Valid
sed -n '^p' emp.txt ⇒ not valid

4)Display multiple lines in the range

sed -n 2,4p emp.txt⇒ it will display 2-4 lines
`sed -n '1p

4p' emp.txt`

5)Display all lines except specific lines

sed -n '1p' emp.txt ⇒ will display first line 
sed -n '1!p' emp.txt 

6)Display all lines except range of lines

sed -n '2,4p' emp.txt =>It will display 2-4 lines 
 sed -n '2,4!p' emp.txt 

Note: We can use cut command to read data column wise ,where we can use sed command to row wise

7)Display all lines having specific word

sed -n ‘/10/’ emp.txt
sed -n '/MANAGER/p' emp.txt

8)Delete data present in given file

While display records,it will delete 3rd record but it won't be deleted from the file

9)Delete line permanently from the file -i is option

sed -i '1d' emp1.txt
Multiple lines delete : sed -i '2,4d' emp1.txt
sed -i '1,$d' emp1.txt ⇒ delete all lines first ti last

10)Display specific independent lines

sed -n -e 2p -e 4p emp.txt  #it will display 2nd and 4 th line 
sed -n -e'2p;4'p emp.txt 

11)To delete specific lines

sed -i -e'1d;3d' emp1.txt   #⇒ 1st line and 3rd line deleted 
sed -i  ‘1d
>$d’ emp.txt

sed -i -e 2d -e 4d emp.txt