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!

!~ statement query

Status
Not open for further replies.

ranjit

Technical User
Apr 14, 2000
131
GB
The below routine increments the month (04 ->05) and year/month if year=12 (12->01, 2004->2005)
The routine runs on all lines beginning with ( YEAR(
I also wanted lines not matching the above string to be printed e.g. test_line

My question is:
Why does the !~ (NOT) statement work at the start and not at the end of the script?

## INPUT FILE##
# cat data
( YEAR(CEN_PROC_DATE) = 2004 and MONTH(CEN_PROC_DATE) = 12 )
( YEAR(CEN_PROC_DATE)=2004 and MONTH(CEN_PROC_DATE)=04 )
( YEAR(AUTH_DATE) = 2004 and MONTH(AUTH_DATE) = 11 )
( YEAR(AUTH_DATE) = 2004 and MONTH(AUTH_DATE) = 09 )
test_line

## NAWK SCRIPT##
# cat nawk.script
nawk '{ FS = "[( )=]+" }

$0 !~/\( YEAR\(/ {print $0} # works here

$0 ~/\( YEAR\(/{
{
# $8 is the month and $4 is the year
if ($8 == 12) {
$8=1
$4++
}
else {$8++ }

printf("( %s(%s)=%s %s %s(%s)=%02d) )\n", $2,$3,$4,$5,$6,$7,$8)

}

## $0 !~/\( YEAR\(/ {print $0} # doesn't work here???

}' data


## RUN SCRIPT##
# ./nawk.script
( YEAR(CEN_PROC_DATE)=2005 and MONTH(CEN_PROC_DATE)=01) )
( YEAR(CEN_PROC_DATE)=2004 and MONTH(CEN_PROC_DATE)=05) )
( YEAR(AUTH_DATE)=2004 and MONTH(AUTH_DATE)=12) )
( YEAR(AUTH_DATE)=2004 and MONTH(AUTH_DATE)=10) )
test_line
 
Everything after a "#" is a comment.

[HIGHLIGHT]#[/highlight]# $0 !~/\( YEAR\(/ {print $0} # doesn't work here???
 
You misunderstand. I left the !~ line of code unhashed in the position where it works and double-hashed it in the place where it doesn't work.

If you were to hash the first !~ statement and unhash the second !~ statement (currently double hashed) the script errors.

From a programming perspective why does the script fail if you use only the second !~ statement (unhashed..of course)?
 
Thi will work:
nawk '{ FS = "[( )=]+" }
$0 ~/\( YEAR\(/{
# $8 is the month and $4 is the year
if ($8 == 12) {
$8=1
$4++
} else {$8++ }
printf("( %s(%s)=%s %s %s(%s)=%02d) )\n", $2,$3,$4,$5,$6,$7,$8)
}
$0 !~/\( YEAR\(/ {print $0} # doesn't work here???
' data
You had an extra { } pair

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top