22
votes

There is a para break at the end of my .csv file. I tried to remove the blank line that is at the end of the file using the following command.

sed -i '/^$/d' combined.csv

But it does not work and a blank line is still there. I can remove the last line using the following command.

sed -i '$d' combined.csv

But is it possible to check if the last line is really empty before removing it?

Update:

I am using the following command to check if each line start with a number.

sed -i '1s/^[^0-9]*//' combined.csv

This checks only for the first line and not the rest of the lines. How do I make it check all the lines in the file? This might solve my problem.

5

5 Answers

34
votes

Try ${/^$/d;} this will only match an empty line if it is the last line of the file.

Update: for your second question, just remove the 1 before the s, i.e.: sed -i 's/^[^0-9]*//' combined.csv

10
votes

Found this ages ago somewhere and saved the snippet. Do not ask me how it works:

perl -i -pe "chomp if eof" combined.csv
1
votes

Try ${/^$/d;} this will only match an empty line if it is the last line of the file.

I tried it with sed (GNU sed) 4.2.2 and got all blank lines deleted not only the empty line if it is the last line of the file.

I found the following Command, that worked for myself that does the Job.

sed -e :a -e '/^\n*$/{$d;N;ba' -e '}'

This Command is from a Collection of useful SED-Oneliners: http://sed.sourceforge.net/sed1line.txt

1
votes

To remove blank lines you can use grep . or sed '/^$/d'

It will remove any blank line in the file. I hope you file does not have any blank lines in the middle but this will work in your case.

cat combined.csv | grep .

or

cat combined.csv | sed '/^$/d'

0
votes

If you know for sure that last line is empty, then just use: ...| head -n -1 | ...