Search & Replace question

Hi all,

I have one question that hopefully isn't too complicated for the more advanced users here. In one of the Solaris KSH scripts I'm working on, is it possible to script the following:

  • If there "is" an empty blank line "at the end" of /tmp/text.txt, then remove only that one empty blank line from the end.
  • If there is "no" empty blank line at the end of /tmp/text.txt, then append an "empty blank line" to the very end of that file.

I'm having difficulty with this one, but I suspect either awk or sed may be needed?
Thank you so much,
cg

 perl -0pe 'if (!s/\n\n$/\n/){s/$/\n/}' /tmp/text.txt > /tmp/text.tmp; mv /tmp/text.tmp /tmp/text.txt
1 Like

Thank you so much, Bartus! Very impressive. I had no idea this could be done in one line of code.

Thanks so much!
cg

# cat infile
3
10 20
10 100
100 1000
EMPTY LINE

del empty line if the end of file

# sed -i '${/^$/d}' infile ; more infile
3
10 20
10 100
100 1000
# cat infile
3
10 20
10 100
100 1000

add empty line if the end of line is not empty line

# sed -i '${/^.*$/!N;$s/\(.*\)/\1\n/;}' infile ; more infile
3
10 20
10 100
100 1000
EMPTY LINE