Results 1 to 6 of 6
Hi,
Easy question hopefully. I have a file with the contents
foo
foo
bar
bar
bar
foo
foo
And I want to add a line 'a pointless line' after the ...
- 10-24-2009 #1Just Joined!
- Join Date
- Oct 2009
- Posts
- 4
sed question
Hi,
Easy question hopefully. I have a file with the contents
foo
foo
bar
bar
bar
foo
foo
And I want to add a line 'a pointless line' after the last line containing the string bar. How would I do this with sed ?
I managed :
sed ' /bar/ a\
a pointless line' < ./foobar.txt
which prints :
foo
foo
bar
a pointless line
bar
a pointless line
bar
a pointless line
foo
foo
So not quite the desired effect as I only wanted it to print:
foo
foo
bar
bar
bar
a pointless line
foo
foo
- 10-25-2009 #2Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
Suppose your_file is
I change the last line to FOO so you know in the result file which line is first which is last, just for identification purpose, it has nothing to do with the commands that I am gonna use.Code:foo foo bar bar bar foo FOO
It would be nice if sed supports searching from the end of the file, in that case the above command can be written asCode:tac your_file | sed '0,/bar/s#bar#pointless line\nbar#' | tac > new_file
A bit of explanation:Code:sed '$,/bar/s#bar#bar\npointless line#' your_file > new_file
tac: the opposite of cat, that is, prints file content from the end to the beginning.
When file is reverse-printed, search from line 0 to the first occurrence of bar and replace that with two lines pointless line\nbar, this in effect inserts pointless line above the first occurrence of bar, then another reverse print gets what you want.
- 10-25-2009 #3Linux User
- Join Date
- Aug 2006
- Posts
- 458
Code:$ more file foo foo bar bar bar foo foo bar $ awk '{a[++d]=$0}/bar/{s=FNR}END{for(i=1;i<=d;i++){if (i==s){print a[i],"\nword"}else{print a[i]}}}' file foo foo bar bar bar foo foo bar word
- 10-25-2009 #4Just Joined!
- Join Date
- Oct 2009
- Posts
- 4
- 10-25-2009 #5Just Joined!
- Join Date
- Oct 2009
- Posts
- 4
- 10-25-2009 #6Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251


Reply With Quote
