Edit
So originally, I've missed the point that OP wants to remove only last blank line, which my original solution does as well. Nonetheless, here's the version that removes only the last one, and if its blank.
awk -v numlines=$(wc -l file2|cut -f1 -d' ') 'NR < numlines; END {if (NF) print }' file2
What the code does is fairly straightforward - get number of lines, and print every line, until the last one. On the last one, we check if the line contains any fields; if there is any text, NF evaluates to an integer (true) thus printing last line, and if there's nothing or spaces only - NF evaluates to zero (false) and doesn't print anything else.
As for removing one more line, head -n -1
will do.
Bellow is the small demo. The trailing newline is designated with $
prompt is *$
*$ cat -A file2
212$
1231$
$
324234$
213$
$
*$ awk -v numlines=$(wc -l file2|cut -f1 -d' ') 'NR < numlines ; END {if ( NF ) print }' file2 | head -n -1
212
1231
324234
Original
awk
solution.
awk 'NF' file1 > /tmp/tmpfile && cat /tmp/tmpfile > file1
Here we use Number of Fields variable as test for printing. For blank lines, number of fields is zero, hence it blank lines evaluating to false won't be printed. Now , unless your awk
version supports in-line editing (which is gnu awk or gawk
, I think), you have to redirect output to temporary output and back to the original file with cat
, like I did here
Variation on the theme would be to use regex to test if lines contain some particular data, like digits or alphanumeric characters, e.g.
awk '$0~/[[:digit:]]||[[:alpha:]]/ ' file1 > /tmp/tmpfile && cat /tmp/tmpfile > file1
$last_line
doesn't get updated, it will fall into thewhile
forever. Also, the standard way to remove empty lines isgrep -v '^\s*$' file
, don't know what else you want to do here but it looks a bit too complicated to involve loops.$
before the curly braces. What is that for?