Friday, 15 January 2016

How to Display Lines Using Sed Command In Unix/Linux

In this article we will see how to use sed command to display the data/records from a file. We will see the use of p switch of sed command with the help of examples.

Display A Particular Line

$ sed -n '3p' F_Input_File.txt

Output: Will display the 3rd line from the file.

p stands for print.

Display Other Than Particular Line

$ sed -n '3 !p' F_Input_File.txt

Output: Will print complete file except the 3rd record. Observe the negate (!) sign, we have used to revert the result of the normal sed command.

Display Lines Between A Provided Range

$ sed -n '3,9p' F_Input_File.txt

Output: Will display lines between ranges 3 to 9.

Display All The Lines Other Than A Provided Range

$ sed -n '3,9!p' F_Input_File.txt

Output: Will print all the lines from the file other than the range 3 to 9.

Display Lines Containing A Required Word

$ sed -n /knowledge/p F_Input_File.txt

Output: Will display all the lines which have Knowledge available in the input file.We have already seen the same using grep and awk in previous post.
Display Lines Which Does Not Contain A Required Word

$ sed -n /knowledge/!p F_Input_File.txt

Output: Will display all the lines which does not have word Knowledge available in the input file.We have seen the same by using -v switch of grep command.

Display Lines Between Two Keywords

$ sed -n /knowledge/,/warehouse/p F_Input_File.txt

Output: Will display all the lines between the lines containing words knowledge and warehouse.

Do Not Display Lines Between Two Keywords

$ sed -n /knowledge/,/warehouse/!p F_Input_File.txt

Output: Will display all the lines other than the lines containing words knowledge and warehouse.
Create Duplicate Lines

$ sed 'p'

Output: p with -n will duplicate the each input line.

If you want to double every empty line, below should be your weapon.

$ sed '/^$/p'
Keep Reading, Keep Learning, Keep Sharing..!!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...