简体   繁体   中英

How to use AWK Using with IF Condition

I need to use AWK command to find count of delimiters in a file and if the count is more than expected then I need to captuure the records.

Code used:

awk 'BEGIN { FS= "^A"; if ( 31 < NF-1) print $0 }'  file.dat

but it is not working.

As fedorqui comments, you don't have any data in a BEGIN block. You have to read at least 1 record to determine how many fields you have:

awk -F"^A" 'NR==1 && NF >= 32 {exit} {print}'  file.dat

Assuming that "^A" is a string of two characters

awk 'BEGIN { FS= "\\^A"} NF-1 > 32'  file.dat

will do, as {print} is the default action for a match and the two most common instances of awk (gawk and mawk) both translate "\\\\^A" to a literal caret followed by the letter A .

On the other hand if "^A" means Control-A you must properly quote the control character when you type the line at the shell prompt (eg, in bash+readline it is Control-V Control-A ) and you must not use the backslashes.

A slightly shorter version:

awk _F"^A" 'NF > 32'  file.dat

Your original construct was 31 < NF-1 which is just a more complex way of saying NF>32 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM