I want to delete 'third' and blanks lines from my.txt below and then store the o/p in my.txt what should be the sed command? Note: this should be in a loop till end of the file
开发者_StackOverflowmy.txt -
first
sec
third
third
third
Using GNU sed, the overwrite is trivial with the '-i
' option; using standard sed, you have to write to a temporary file and then copy that over the original.
The other answers pre-date the 'blank lines' requirement in the question.
sed -i '/third/d;/^[ ]*$/d' my.txt
The first part of the command, up to the semi-colon, looks for 'third' and deletes any matching line. The second part of the command looks for any line consisting of zero or more blanks and deletes them. If you want to delete lines with blanks and tabs, add a tab in the character class -- there isn't a convenient way to show tabs in the SO markup language.
You could equivalently write:
sed -i -e '/third/d' -e '/^[ ]*$/d' my.txt
And for non-GNU sed, you would use:
sed '/third/d;/^[ ]*$/d' my.txt > x.$$
cp x.$$ my.txt
rm -f x.$$
You can do:
sed -i -r '/^(third|)$/d' my.txt
sed -i 's/third//g' my.txt
would modify the file in-place.
sed
is a stream editor, i.e. it is for editing streams (pipes) not files. If you want to edit files, you should use a file editor such as ed
:
ed my.txt <<-HERE
,g/^third$/d
,g/^$/d
w
q
HERE
精彩评论