Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK remove blank lines

Tags:

linux

awk

The /./ is removing blank lines for the first condition { print "a"$0 } only, how would I ensure the script removes blank lines for every condition ?

awk -F, '/./ { print "a"$0 } NR!=1 { print "b"$0 } { print "c"$0 } END { print "d"$0 }' MyFile
like image 641
general exception Avatar asked Apr 27 '12 08:04

general exception


People also ask

How do you delete blank lines in awk?

We can remove blank lines using awk: $ awk NF < myfile.

How do I remove blank lines in Unix?

The d command in sed can be used to delete the empty lines in a file. Here the ^ specifies the start of the line and $ specifies the end of the line. You can redirect the output of above command and write it into a new file.


4 Answers

A shorter form of the already proposed answer could be the following:

awk NF file

Any awk script follows the syntax condition {statement}. If the statement block is not present, awk will print the whole record (line) in case the condition is not zero.

NF variable in awk holds the number of fields in the line. So when the line is non empty, NF holds a positive value which trigger the default awk action (print the whole line). In case of empty line, NF is zero and the condition is not met, so awk does nothing.

Note that you don't even need quote because this 2 letters awk script doesn't contain any space or character that could be interpreted by the shell.


or

awk '!/^$/' file

^$ is the regex for an empty line. The 2 / is needed to let awk understand the string is a regex. ! is the standard negation.

like image 56
oliv Avatar answered Oct 08 '22 18:10

oliv


Awk command to remove blank lines from a file:

awk 'NF > 0' filename
like image 41
Aaykay Avatar answered Oct 08 '22 18:10

Aaykay


if you want to ignore all blank lines, put this at the beginning of the script

/^$/ {next}
like image 29
glenn jackman Avatar answered Oct 08 '22 18:10

glenn jackman


Put following conditions inside the first one, and check them with if statements, like this:

awk -F, '
    /./ { 
        print "a"$0; 
        if (NR!=1) { print "b"$0 } 
        print "c"$0 
    } 
    END { print "d"$0 }
' MyFile
like image 38
Birei Avatar answered Oct 08 '22 18:10

Birei