TheFox
TheFox

Reputation: 502

SED adds new line at the end

If I execute this on Mac OS X 10.7.2 in the Terminal App:

$ cat test.txt | od -c

I get

0000000    t   e   s   t   1  \n   t   e   s   t   2                    
0000013

That's the real content of my test.txt file. Ok.

But if I execute sed it adds a new line of each file.

$ sed 's/e/X/g' test.txt | od -c
0000000    t   X   s   t   1  \n   t   X   s   t   2  \n                
0000014

I don't want this new line. How can I fix this?

Upvotes: 1

Views: 2313

Answers (1)

Michael J. Barber
Michael J. Barber

Reputation: 25042

Use printf in awk. Special case the first line so that it is printed without a newline. All remaining lines are printed with a preceding newline. This ensures that you never end with a newline.

Basic structure:

awk 'NR==1 { printf("%s", $0); next }
     { printf("\n%s", $0) }'

Upvotes: 1

Related Questions