tags:

views:

305

answers:

3

How do I combine two specific adjacent lines in a large text file into one line using sed? For example I want to combine line numbered 2001891 and 2001892 into one line, and write it back to the file at the same line location (meaning line 2001893 and below will get shifted up)?

I've googled around for tutorials and manuals on sed but all are too cryptic to me (those '2,3p;N;s/jam.l,21/.,lk;dczA[12]blahblah' means what?)

A: 
$ awk 'NR==2001891{printf $0;getline;print;next}1' file > temp;mv temp file

OR

$ awk '{printf (NR==2001891)?$0:$0"\n"}' file  > temp;mv temp file
ghostdog74
A: 

I am sure you can do some simple magic using cat, file redirection, and nl command.

Hamish Grubijan
No, you cannot.
Dennis Williamson
What makes you so sure?
Hamish Grubijan
+4  A: 

I am not a sed guru, but I think you want:

sed -i '2001891N;s/\n//' filename

(Try it without -i on a test file before running it on important data, of course.)

$ cat a.dat
1
2
3
4
$ sed '2N;s/\n//' a.dat 
1
23
4

I tried the simpler sed '2001891s/\n//', but it doesn't work when the pattern is \n. For any other pattern (sed '2001891s/a//' for example), it seems to work. It's too late in the night for me to think about it more, but I hope one of the sed gurus will explain what's going on with my simpler sed command.

Alok
To explain what's going on here: the `2001891` is the `address`; it tells `sed` to only operate on lines that match this pattern. `N` tells sed to append the next line into the `pattern space` (ie, the text it's currently working on). `;` starts a new command, and finally `s/\n//` strips out the newline character.
James Polley
Yeah, I was going to add an explanation, but you did before me. Thanks!
Alok
The `s` and `y` commands of `sed` don't see the newline at the end of the pattern (or hold) space (only ones that appear before the end).
Dennis Williamson
@Dennis. Thanks a lot!
Alok