Delete first line of file if empty

How can I delete the first (!) Line of a text file if it is empty using, for example, 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 is empty. Can I give sed some condition regarding line number?

With Levon's answer, I built this little awk-based script:

 #!/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 
+6
source share
6 answers

The simplest thing in sed:

 sed '1{/^$/d}' 

Note that this does not delete the line containing all the spaces, but only the line containing only one new line. To get rid of spaces:

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

and eliminate all the gaps:

 sed '1{/^[[:space:]]*$/d}' 
+11
source

If you don't need to do this in place, you can use awk and redirect the output to another file.

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

This will print the contents of the file except the first line ( NR == 1 ) and does not contain any data ( NF == 0 ).

NR number of the current line, NF number of fields on this line, separated by spaces / tabs

eg.

 $ 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 an in-place replacement:

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

The original file will be saved with the extension .bak

+2
source

Using sed, try the following:

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

or make changes to the place:

 sed -i~ -e '2,$b' -e '/^$/d' somefile 
+1
source

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'

+1
source

This might work for you:

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

The original answer is correct, something superfluous: if you want to do it recursively and limit it to one type of file, then this will do the following.

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

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

0
source

Source: https://habr.com/ru/post/919130/


All Articles