1753471 Members
4984 Online
108794 Solutions
New Discussion юеВ

Re: 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 4
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.