Delete first line of file if it's empty

2019-03-19 09:12发布

问题:

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

回答1:

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}'


回答2:

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


回答3:

If you don't have to do this in-place, you can use awk and redirect the output into a different file.

awk '{if (NR==1 && NF==0) next};1' somefile

This will print the contents of the file except if it's the first line (NR == 1) and it doesn't contain any data (NF == 0).

NR the current line number,NF the number of fields on a given line separated by blanks/tabs

E.g.,

$ cat -n data.txt
     1  
     2  this is some text
     3  and here
     4  too
     5  
     6  blank above
     7  the end

$ awk '{if (NR==1 && NF==0) next};1' data.txt | cat -n
     1  this is some text
     2  and here
     3  too
     4  
     5  blank above
     6  the end

and

cat -n data2.txt
     1  this is some text
     2  and here
     3  too
     4  
     5  blank above
     6  the end

$ awk '{if (NR==1 && NF==0) next};1' data2.txt | cat -n
     1  this is some text
     2  and here
     3  too
     4  
     5  blank above
     6  the end

Update:

This sed solution should also work for in-place replacement:

sed -i.bak '1{/^$/d}'  somefile

The original file will be saved with a .bak extension



回答4:

Delete the first line of all files under the actual directory if the first line is empty :
find -type f | xargs sed -i -e '2,$b' -e '/^$/d'



回答5:

The initial answer is correct, something extra: if you are looking to do this recursively and limit it to one filetype then the following will do that.

find . -name "*.py" -print0 | xargs -0 sed -i '1{/^$/d}'

The above example searches the current directory down, for all *.py files (Python files). Change the extension, change which files it enacts on.



回答6:

This might work for you:

sed '1!b;/^$/d' file


标签: shell unix sed