Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete first line of file if it's empty

Tags:

shell

unix

sed

How can I delete the first (!) line of a text file if it's empty, using e.g. sed or other standard UNIX tools. I tried this command:

sed '/^$/d' < somefile

But this will delete the first empty line, not the first line of the file, if it's empty. Can I give sed some condition, concerning the line number?

With Levon's answer I built this small script based on awk:

#!/bin/bash

for FILE in $(find some_directory -name "*.csv")
do
    echo Processing ${FILE}

    awk '{if (NR==1 && NF==0) next};1' < ${FILE} > ${FILE}.killfirstline
    mv ${FILE}.killfirstline ${FILE}

done
like image 692
Arne Avatar asked Jun 27 '12 13:06

Arne


People also ask

How do I remove the first line of a text file in Unix?

sed is a common text processing utility in the Linux command-line. Removing the first line from an input file using the sed command is pretty straightforward. The sed command in the example above isn't hard to understand. The parameter '1d' tells the sed command to apply the 'd' (delete) action on line number '1'.

How do I remove the first line from a csv file in Unix?

To remove the first 2 lines from all files (resulting in an output with no header), just use awk 'FNR>2' or with GNU sed : sed -s 1,2d or with GNU tail or compatible (including ast-open, FreeBSD and busybox): tail -qn+3 .

How do I show the first line of a text file?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>.


2 Answers

The simplest thing in sed is:

sed '1{/^$/d}'

Note that this does not delete a line that contains all blanks, but only a line that contains nothing but a single newline. To get rid of blanks:

sed '1{/^ *$/d}'

and to eliminate all whitespace:

sed '1{/^[[:space:]]*$/d}'
like image 93
William Pursell Avatar answered Oct 21 '22 10:10

William Pursell


Using sed, try this:

sed -e '2,$b' -e '/^$/d' < somefile

or to make the change in place:

sed -i~ -e '2,$b' -e '/^$/d' somefile
like image 20
Rob Davis Avatar answered Oct 21 '22 10:10

Rob Davis