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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK command with IF statement. 1

Status
Not open for further replies.

scfc1976

Programmer
May 19, 2009
12
GB
Hi all.

As a new user of AWK and a inexperienced programmer I could use a bit of help with a little problem.

I have a file that could change depending on what users are acessing the file. This file is then used to update information on a database.

File example:

"Text","data","word","word1"
"number(1)","stuff","char","mumber2"
1,"B","data",.1
2,"A","words",
1,"H","stuff",999.99
1,"W","morewords",
...

The length of the file may change and the only data inputted data would fill the first 3 fields.

Basically I would need the output in the following format for the database to handle it.

1,"B","data",.1
2,"A",words",1 (any number would do in field 4)
1,"H","stuff",999.99
1,"W",morewords",1
etc

Note that any line that doesn't begin with a single number can be ignored for input to the database. And the 4th field must contain a number.

At present I have the following code:-

awk -F, '/^[0-9]/ { if ( $4 !~/^[0-9]/ ) $4 ="1" } {print $4 }

While this produces a seies of 1's in field 4 it removes any leading decimal points and replaces it with a 1 and also outputs $4 on the two lines that need to be ignored.

Any help to get around this would be most appreciated.

Thanks in advance.
 
Try this perhaps:

Code:
awk -F, -v OFS=, '/^[0-9]/ { if ($4 !~ /^[0-9]*\.?[0-9]+/) $4 = "1"; print }'

Because you had your print in a separate set of braces it was being executed for every input line, it was no longer goverened by the /^[0-9]/ expression which only applies to the code block immediately following it.

Annihilannic.
 
Annihilannic.

It does the job perfectly. I would have spent hours / days on that.

Thank you.

scfc1976
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top