Volodymyr Bezuglyy
Volodymyr Bezuglyy

Reputation: 16805

Why sed removes last line?

$ cat file.txt
one
two
three
$ cat file.txt | sed "s/one/1/"
1
two

Where is the word "three"?

UPDATED: There is no line after the word "three".

Upvotes: 5

Views: 3566

Answers (6)

Kristianw
Kristianw

Reputation: 89

Using comments from other posts:

  1. older versions of sed do not process the last line of a file if no EOL or "new line" is present.
  2. echo can be used to add a new line

Then, to solve the problem you can re-order the commands:

( cat file.txt && echo ) | sed 's/one/1/'

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342403

here's an awk solution

awk '{gsub("one","1")}1' file.txt

Upvotes: 0

Wooble
Wooble

Reputation: 89917

A google search shows that the man page for some versions of sed (not the GNU or BSD versions, which work as you'd expect) indicate that it won't process an incomplete line (one that's not newline-terminated) at the end of a file. The solution is to ensure your files end with a newline, install GNU sed, or use awk or perl instead.

Upvotes: 1

GreenMatt
GreenMatt

Reputation: 18580

Instead of cat'ing the file and piping into sed, run sed with the file name as an argument after the substitution string, like so:

sed "s/one/1/" file.txt

When I did it this way, I got the "three" immediately following by the prompt:

1
two
three$

Upvotes: 1

Ivan Nevostruev
Ivan Nevostruev

Reputation: 28723

I guess there is no new line character after last line. sed didn't find line separator after last line and ignore it.

Update

I suggest you to rewrite this in perl (if you have it installed):

cat file.txt | perl -pe 's/one/1/'

Upvotes: 1

jamessan
jamessan

Reputation: 42667

As Ivan suggested, your text file is missing the end of line (EOL) marker on the final line. Since that's not present, three is printed out by sed but then immediately over-written by your prompt. You can see it if you force an extra line to be printed.

sed 's/one/1/' file.txt && echo

This is a common problem since people incorrectly think of the EOL as an indication that there's a following line (which is why it's commonly called a "newline") and not as an indication that the current line has ended.

Upvotes: 4

Related Questions