Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to ignore blank lines and comment lines using awk

i am writing this code:

awk -F'=' '!/^$/{arr[$1]=$2}END{for (x in arr) {print x"="arr[x]}}' 1.txt 2.txt

this code ignore blank lines, but i also want to ignore line starting with # (comments).

Any idea how to add multiple patterns?

like image 352
kumar Avatar asked Jun 29 '12 18:06

kumar


People also ask

How do I skip blank lines in awk?

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

How do you ignore in awk?

The IGNORECASE is a built in variable which can be used in awk command to make it either case sensitive or case insensitive. If the IGNORECASE value is 0, then the awk does a case sensitive match. If the value is 1, then the awk does a case insensitive match.

How do I use NF in awk?

NF is a predefined variable whose value is the number of fields in the current record. awk automatically updates the value of NF each time it reads a record. No matter how many fields there are, the last field in a record can be represented by $NF . So, $NF is the same as $7 , which is ' example.

What does 1 mean in awk?

1 means to print every line. The awk statement is same as writing: awk -F"=" '{OFS="=";gsub(",",";",$2);print $0;}' Copy link CC BY-SA 3.0.


2 Answers

Change !/^$/ to

!/^($|#)/

or

!/^($|[:space:]*#)/

if you want to disregard whitespace before the #.

like image 137
chaos Avatar answered Oct 16 '22 07:10

chaos


awk 'NF && $1!~/^#/' data.txt

Will print all non-blank lines (number of fields NF is not zero) and lines that don't contain # as the first field.

It will handle a line of whitespace correctly since NF will be zero, and leading blanks since $1 will ignore them.

like image 41
Levon Avatar answered Oct 16 '22 08:10

Levon