Friday, 3 August 2018

Linux: sed - Delete a line

As we discussed in the above section about the power of SED command, here we discuss about the how to use SED command to delete a line in a file.
How to delete first line using SED command
sed 'Nd' sample1.txt
Note: ‘N’should be replaced with the line number which we want to delete 
           ‘d’ is the command used to delete.
How to delete a particular line using SED command
sed '4d' sample1.txt

How delete last line in a file using SED command
sed '$d' sample1.txt
Note: ‘$ ‘indicates the last line of a file
In the next article will learn more about SED commands.

Delete all spaces in front of every line of file.txt
sed 's/^[ ^t]*//' file.txt


Delete all spaces at the end of every line of file.txt
sed 's/[ ^t]*$//' file.txt
Delete all spaces in front and at the end of every line of file.txt
sed 's/^[ ^t]*//;s/[ ^]*$//' file.txt

Delete all consecutive blank lines except for EOF
sed '/./,/^$/!d' file.txt
Delete all consecutive blank lines, but allows only top blank line
sed '/^$/N;/\n$/D' file.txt

Delete all leading blank lines
sed '/./,$!d' file.txt

Delete all trailing blank lines
sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' \file.txt

Delete every third line, starting with the first
sed '1~3d' file.txt

Delete only the first match
sed '0,/RE/{//d;}' file.txt
Delete lines matching pattern
sed '/pattern/d' file.txt

Delete all blank lines from a file
sed '/./!d' file.txt

Delete all consecutive blank lines except for the first two
sed '/^$/N;/\n$/N;//D' file.txt

Delete the last line of each paragraph
sed -n '/^$/{p;h;};/./{x;/./p;}'\ file.txt








0 comments:

Post a Comment