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 |
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 |
Hi.
With sed: Code:
$ cat infile |
I recommend using ed for this instead.
Code:
printf '%s\n' '1,2j' 'w newfile.txt' | ed -s infile.txt 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) |
Quote:
Daniel B. Martin |
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. |
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. |