LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Appending ends of lines in sed (https://www.linuxquestions.org/questions/programming-9/appending-ends-of-lines-in-sed-660977/)

Agentrooker 08-06-2008 04:30 PM

Appending ends of lines in sed
 
Suppose I have two text files with the same number of lines. Is there a way for me to use sed to append the lines from one text file to the end of the lines for another? For example:

file "foo" contains:
Apple
Basket
Crispy

file "bar" contains:
pie
ball
rice

And the resulting file "foobar" should be:
Apple pie
Basket ball
Crispy rice

Can anyone tell me how to go about doing this?

theNbomr 08-06-2008 05:02 PM

If I conclude that you want to use sed because it should be a one-liner, I will offer instead a Perl one-liner:
Code:

perl -e 'open(FOO,"foo"); open(BAR,"bar");while($foo=<FOO>){ $bar=<BAR>; chomp $foo; print "$foo $bar";}'
--- rod.

kenoshi 08-06-2008 05:37 PM

Do you really need to use sed? How's about:

Code:

paste -d\  foo bar > foobar

Kenhelm 08-06-2008 08:31 PM

This uses GNU sed:-
Code:

sed 'R bar' foo | sed 'N;s/\n/ /' > foobar

chakka.lokesh 08-07-2008 12:19 AM

Quote:

Originally Posted by Kenhelm (Post 3239295)
This uses GNU sed:-
Code:

sed 'R bar' foo | sed 'N;s/\n/ /' > foobar

I tried this

Code:

sed 'R file2; s/\n//' file1
but it didn't work. I don't know why? can u please tell me why ?

thanks.

burschik 08-07-2008 12:39 AM

Code:

paste -d\  foo bar

Agentrooker 08-07-2008 08:55 AM

Thanks everyone. I don't know why I assumed I had to do it with sed, but I wasn't aware of the paste command. That ended up being a pretty elegant solution to my problem. Thanks again.

Kenhelm 08-07-2008 10:18 AM

Quote:

Originally Posted by chakka.lokesh
I tried this
sed 'R file2; s/\n//' file1
but it didn't work. I don't know why? can u please tell me why ?
On my system the R command takes the full string after it upto the quote as the filename.
So in your example it would be looking for a file named "file2; s/\n//" not one named "file2".

Also the inserted lines are put into the output stream not into the pattern space.

chakka.lokesh 08-07-2008 11:19 PM

Quote:

Originally Posted by Kenhelm (Post 3239958)
On my system the R command takes the full string after it upto the quote as the filename.
So in your example it would be looking for a file named "file2; s/\n//" not one named "file2".

Also the inserted lines are put into the output stream not into the pattern space.

got it.

thx


All times are GMT -5. The time now is 03:05 AM.