Monday, November 30, 2009

Awk - extract negative numbers from file


Posting this entry so that awk newbies will see the use of awk NF,NR variables along with some basic awk 'for' and 'if constructs' use.

Input file:

$ cat file.txt
-5232,-92338,84545,34
-2233,25644,23233,2
6211,-1212,4343,43
-2434,621171,9121,-33

Required: Extract the numbers which starts with '-'

Solution using bash tr (command to translate or delete characters)

$ tr ',' '\n' < file.txt | grep ^-
Output:
-5232
-92338
-2233
-1212
-2434
-33

Using awk:

$ awk -F "," '
{for(i=1; i<=NF;i++)
if($i ~ /^-/) {printf "%s\n",$i}
}
' file.txt

Extending the above one liner to print the line number and field number where the negative value is present.

$ awk -F "," '
{for(i=1; i<=NF;i++)
if($i ~ /^-/) {
printf "Line # %s,Field # %s,Value = %s\n",NR,i,$i
}
}' file.txt

Output:
Line # 1,Field # 1,Value = -5232
Line # 1,Field # 2,Value = -92338
Line # 2,Field # 1,Value = -2233
Line # 3,Field # 2,Value = -1212
Line # 4,Field # 1,Value = -2434
Line # 4,Field # 4,Value = -33

Related posts:

- Awk for loop
- Awk if else
- Awk variables

2 comments:

voyeg3r said...

Alternate RS :)

awk 'BEGIN {RS=",|\n"}/^-/ {print}' file.txt

Jadu Saikia said...

@Voyeg3r, thank you so much, its a good one.

© Jadu Saikia www.UNIXCL.com