perl + append WORD in the end of the last line in the file

2

I use the following perl one line in order to append WORD in the end of the last line in the file

     perl -p -i -e 's/$/WORD/;' file

But it's append the WORD in every line -

How to fix the perl syntax in order to append the WORD only on the last line in the file

example

  more file

  AAAAA BBB
  WWWWW
  EEEEE WORD

jennifer

Posted 2010-10-12T13:20:50.110

Reputation: 897

Answers

4

You need to detect that you''ve hit the end-of-file using eof:

perl -p -i -e 'eof && s/$/WORD/;'  file

martin clayton

Posted 2010-10-12T13:20:50.110

Reputation: 1 012

2

Here's an equivalent using sed:

sed -ie '$s/$/WORD/' file

Paused until further notice.

Posted 2010-10-12T13:20:50.110

Reputation: 86 075

1

Just add the -0 flag:

perl -0pie 's/$/WORD/' file

I'd never use -i without an added extension by the way. If your Perl doesn't do what you intended, your input will be lost. By the way, ; is not a statement terminator in Perl, but a statement separator.

perl -i.orig -0pe 's/$/WORD/' file

Another handy idiom, for testing:

perl -0pe 's/$/WORD/' file | diff file -

reinierpost

Posted 2010-10-12T13:20:50.110

Reputation: 1 904