Operating System - HP-UX
1819804 Members
2829 Online
109607 Solutions
New Discussion юеВ

Re: remove blank line from end of ascii file

 
Rpger Tavener
Occasional Advisor

remove blank line from end of ascii file

Within a script, how can I test to see if the last line in an ascii file contains nothing but blanks and if it does , remove the last line of the file.

Thanks
When the only tool you own is a hammer, every problem looks like a nail!
6 REPLIES 6
Thierry Poels_1
Honored Contributor

Re: remove blank line from end of ascii file

hi,

ed yourfile << EOT
\$g/^\$/d
w
q
EOT

( $g/^$/d : search through last line, for empty line & delete). Should work if it's not an extremely large file.

good luck,
Thierry.
All unix flavours are exactly the same . . . . . . . . . . for end users anyway.
Deepak Extross
Honored Contributor

Re: remove blank line from end of ascii file

Try this:
#!/usr/bin/ksh
if [ `tail -i yourfile | tr -d " " | tr -d "\t" | wc -c` -eq 1 ]
then
lines=`wc -l yourfile | cut -d" " -f1`
head -`expr $lines -1` yourfile > yourfile.out
mv -f yourfile.out yourfile
fi

In case you want spaces and tabs on the last line to be considered as valid non-blank characters, just delete the 'tr -d' commands on the first line.
Hope this helps.
Deepak Extross
Honored Contributor

Re: remove blank line from end of ascii file

oops..a typo.
Replace the "tail -i yourfile" in the first line of my script with "tail -1 yourfile"
SHABU KHAN
Trusted Contributor

Re: remove blank line from end of ascii file

Roger,

Here is a simple script that can do the job for you :

You can make it more meaningful and efficient by adding more print statements

#!/bin/ksh

grep "^$" testthis | tail -1 > testthis.out

if [[ -s testthis.out ]]; then
print "Blank line exists in the last line of this file"
rm -f testthis.out
else
print "Blank line does not exist in the last line of this file"
fi

-Shabu
SHABU KHAN
Trusted Contributor

Re: remove blank line from end of ascii file

oops !

I didn't read your posting properly, thought you wanted the file removed...
Anyway... if there is a blank line in an ascii file and if you would like that blank line removed then do:

#!/bin/ksh

grep "^$" testthis | tail -1 > testthis.out
if [[ -s testthis.out ]]; then
print "Blank line exists in the last line of this file"
print "Removing blank line.. newfile is cleanfile.out
sed '/^$/d' testthis > cleanfile.out
else
print "Blank line does not existin the last line of this file"
fi

-Shabu
Robin Wakefield
Honored Contributor

Re: remove blank line from end of ascii file

Hi Roger,

...and using awk...

awk 'NR==1{line=$0;next}
{print line;line=$0}
END{if (line !~ /^[ ]*$/)print line}' yourfile

The square brackets contain -space- followed by -tab-

Rgds, Robin