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
  • 1,117

3 Answers3

4

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

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

Here's an equivalent using sed:

sed -ie '$s/$/WORD/' file
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
  • 2,240