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!

Beginner - Modifying fields in a file

Status
Not open for further replies.

dukes82

Programmer
Oct 13, 2004
2
US
I'm learning to script with gawk, and have a small problem.
I have a file that represents a stock sheet
name1|18
name2|15
name3|4

I'm trying to modify the last field.
Is there a way to do this using print >> statements?
does print >> always append to the end of a file, even if
it's open?
Basically, i have a number x, the name2 value, and want to replace 15 with 15-x. Is there a simple(conceptually) way to do this?
I apologize if this is a simple question, I searched for similar problems but i just don't know enough about gawk to understand the solutions i saw.
 
Something like this ?
gawk -v n="name2" -v x=someValue -F '|' '
BEGIN{OFS=FS}
$1==n{$2-=x}
{print}
' /path/to/input > output

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
i'm running gawk from inside a cgi file, not the command line.
so i'm a little confused.
i think you're saying,
#! path/to/gawk -f
begin {
OFS=FS
if ($1==n) $2-=x
print >output
}
but i'm not sure what the apostrophe after print is doing and what exactly OFS=FS is doing.

 
I'm not familiar with cgi, but this should be adaptable to your needs:
Code:
BEGIN { FS="|"; OFS=FS }
$1==name { $2 -= x }
9

Save this as, say, "modstock.awk".

Run it with something like
[tt]
gawk -f modstock.awk name="name2" x=5 datafile >outfile
[/tt]
If outfile already exists and you want to append to it, use ">>outfile".

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top