LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Concatenate the first 2 lines of a file (https://www.linuxquestions.org/questions/programming-9/concatenate-the-first-2-lines-of-a-file-4175419812/)

meetmefar 08-01-2012 02:18 PM

Concatenate the first 2 lines of a file
 
Hi Gurus,
I have a text file with many lines in it. I would like just to concatenate the first 2 lines and the remaining lines as it is into a new file.

Input file:

abcdef
stuvw
pqrst
xyz

output:

abcdefstuvw
pqrst
xyz

I am able to do it with looping throigh the lines and printing on to the new file. Is it possible to get a sed or perl command to do it?

Thanks,
meetmefar

Snark1994 08-01-2012 02:43 PM

I don't have a linux machine with me to experiment on (holidays, y'see ;)) but you could do it with awk; something like (absolutely untested)

Code:

awk 'BEGIN={acc = "";} { if(NR == 1){ acc = $0 } else if (NR == 2){ print acc, $0 } else { print $0 } }' infile

firstfire 08-01-2012 02:52 PM

Hi.

With sed:
Code:

$ cat infile
abcdef
stuvw
pqrst
xyz
$ sed '1{N;s/\n//}' infile
abcdefstuvw
pqrst
xyz

If we are at 1st line, then append next line (N) to pattern space (now pattern space looks like "line1\nline2") and remove newline (\n) character.

David the H. 08-02-2012 09:07 AM

I recommend using ed for this instead.

Code:

printf '%s\n' '1,2j' 'w newfile.txt' | ed -s infile.txt
The 'j' command joins lines together. The 'w' command writes the changes to a file. Used alone it writes back to the original, or with an argument you can create a new file.

Use '%p' to print the modifications to stdout.

Note also that if you need a space or something between the merged lines you'll need to add another command to insert it first.

Code:

printf '%s\n' '1s/$/ /' '1,2j' 'w newfile.txt' | ed -s infile.txt

How to use ed:
http://wiki.bash-hackers.org/howto/edit-ed
http://snap.nlc.dcccd.edu/learn/nlc/ed.html
(also read the info page)

danielbmartin 08-02-2012 09:22 AM

Quote:

Originally Posted by David the H. (Post 4744112)
I recommend using ed for this instead. ...

It is helpful for newbies (such as me) to know why you recommend something. Faster execution? More readable code? Something else?

Daniel B. Martin

David the H. 08-02-2012 09:50 AM

Maybe I shouldn't have used the word "instead". Either way will work just fine.

I like ed because it's light, the expressions needed in this case are clearer and more intuitive, and you can write out directly to a file, even back to the original. Of course you do need to use a pipe or similar to feed the commands to ed through stdin, so perhaps it's a wash.

meetmefar 08-03-2012 02:04 PM

Thank you everyone who contributed. I used the sed command, may be because I am used to it.

meetmefar


All times are GMT -5. The time now is 09:33 AM.