Simpler Navigation for Servers and Operating Systems - Please Update Your Bookmarks
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
If you have bookmarked forums or discussion boards in Servers and Operating Systems, we suggest you check and update them as needed.
cancel
Showing results for 
Search instead for 
Did you mean: 

script

SOLVED
Go to solution
Chapaya
Frequent Advisor

script

Is there a way to append a new string to a line which is in the middle of a file.


For eg: below is my file
first line of text
second line of text
third line of text
fourth line of text


i want a output like this:
first line of text
second line of text New string added here
third line of text
fourth line of text
4 REPLIES
Fredrik.eriksson
Valued Contributor
Solution

Re: script

Hi

One way is doing like this.
# sed -e "/second line/ a\test" temp
first line of text
second line of text
test
third line of text
fourth line of text

Another if you know specific row number.
# sed -e "2 a\test" temp
first line of text
second line of text
test
third line of text
fourth line of text

The above version is just search and add, make sure (if you're going to use that) that you have a exact match.

Otherwise you can end up like this:
# sed -e "/text/ a\test" temp
first line of text
test
second line of text
test
third line of text
test
fourth line of text
test

Best regards
Fredrik Eriksson
Wilfred Chau_1
Respected Contributor

Re: script

assuming your text is in myfile. This command will append "new string" including a new line character to end of line that matches "third line of text" and then redirect the result to "newfile"

perl -ne 'if ($_ =~ /^third line of text/i) {$_ =~ s/[\r\n]+//; $_ .= " new string\n";} print "$_";' myfile > newfile
Ciro Iriarte
Valued Contributor

Re: script

That would add a new line to the stream, this would append a string to the line that matches in the stream:

sed -e "/second line of text/ s/.*/& New string added here/" test

Regards,
Chapaya
Frequent Advisor

Re: script

thanks all.