Delete first line of file if it's empty

后端 未结 5 1118
再見小時候
再見小時候 2021-02-07 22:06

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         


        
相关标签:
5条回答
  • 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
    
    0 讨论(0)
  • 2021-02-07 23:00

    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'

    0 讨论(0)
  • 2021-02-07 23:08

    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}'
    
    0 讨论(0)
  • 2021-02-07 23:08

    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

    0 讨论(0)
  • 2021-02-07 23:08

    This might work for you:

    sed '1!b;/^$/d' file
    
    0 讨论(0)
提交回复
热议问题