Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help Understanding Awk Syntax 1

Status
Not open for further replies.

johngiggs

Technical User
Oct 30, 2002
492
US
I can't seem to figure out something with awk.

When I type:

awk '/^[0-9]{5}/{print $1}' filename

it will only print lines that begin with 5 numeric characters.

When I type:

awk '/^[0-9]{5}/{if ($4 !~ "[A-Z]$") $4 = "X"}{print substr($2,1,1), substr ($4,1,1), substr ($3,1,1)}' filename

it prints lines all lines, even if they do not begin with 5 numeric characters.

Can someone please explain why the second example doesn't just print the lines that begin with 5 numeric characters?

Any help would be greatly appreciated.

Thanks,

John
 
awk '/^[0-9]{5}/{if ($4 !~ "[A-Z]$") $4 = "X"}{print substr($2,1,1), substr ($4,1,1), substr ($3,1,1)}' filename
Your script can be read like this:
awk '
/^[0-9]{5}/{if ($4 !~ "[A-Z]$") $4 = "X"}
{print substr($2,1,1), substr ($4,1,1), substr ($3,1,1)}
' filename
You have no pattern selection for the print action.
I guess your intent was something like this:
awk '/^[0-9]{5}/{
if ($4 !~ "[A-Z]$") $4 = "X"
print substr($2,1,1), substr ($4,1,1), substr ($3,1,1)
}' filename

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Code:
awk '
/^[0-9]{5}/ {
   if ($4 !~ "[A-Z]$") $4 = "X"
}
{
print substr($2,1,1), substr ($4,1,1), substr ($3,1,1)
}' filename

The code of an awk script is in the form :
pattern { action } ...

Pattern select records. If no pattern is specified all records are selected.
In your code, there is two pattern/action.

1) Select records starting with five numeric chars {
change field 4 to X if not a single alphabetic character }

2) Select all records { print first char of fields 2, 4 and 3 }



Jean Pierre.
 
Thanks, PHV. I guess I had an extra set of brackets.

John
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top