We can use the sed command to retrieve and edit data present in the given file. We can perform operations based on lines, like deleting the 2nd line, etc. We can also perform operations based on content, like deleting lines where the word "python" is present, etc.
Example file: emp.dat
eno|ename|esal|eaddr|dept|gender
100|sunny|1000|mumbai|admin|female
200|bunny|2000|chennai|sales|male
300|chinny|3000|delhi|accounting|female
400|vinny|4000|hyderabad|admin|male
500|pinny|5000|mumbai|sales|female
$ sed '2p' emp.datpmeans print.- It will display the entire file content, but the 2nd line will be displayed twice.
Example output:
eno|ename|esal|eaddr|dept|gender
100|sunny|1000|mumbai|admin|female
100|sunny|1000|mumbai|admin|female
200|bunny|2000|chennai|sales|male
300|chinny|3000|delhi|accounting|female
400|vinny|4000|hyderabad|admin|male
500|pinny|5000|mumbai|sales|female
$ sed -n '3p' emp.dat-nmeans suppress automatic printing.3pmeans print the 3rd line.
Alternatively, you can use:
$ head -n 3 emp.dat | tail -n 1head -n 3prints the first 3 lines.tail -n 1prints the last line of the output fromhead, which is the 3rd line.- This will display only the 3rd line.
$ sed -n '$p' emp.dat$means the last line.
$ sed -n '2,4p' emp.dat- It will display lines from 2nd to 4th.
$ sed -n '2p
> 4p' emp.datAlternatively, you can use:
$ sed -n -e '2p' -e '4p' emp.dator:
$ sed -n -e '2p;4p' emp.dat$ sed -n '2!p' emp.dat- It will display all lines except the 2nd line.
$ sed -n '2,4!p' emp.dat- It will display all lines except for lines 2 to 4.
$ sed -n '/admin/p' emp.dat- It will display all lines that contain the word "admin."
$ sed '3d' emp.datdmeans delete.- It deletes the 3rd record while displaying but does not modify the file.
$ sed '$d' emp.dat- Deletes the last record.
$ sed '1d' emp.dat- Deletes the first record.
$ sed -i '5d' emp.dat-imeans it modifies the file in place and deletes the 5th record permanently.
$ sed -i '1,$d' emp.dat- Deletes all records from the 1st to the last in the file.
$ sed -i '1d
> $d' emp.dat- Deletes the first and last records.