1833451 Members
3064 Online
110052 Solutions
New Discussion

AWK script

 
SOLVED
Go to solution
Chern Jian Leaw
Regular Advisor

AWK script

Hi

I have an AWK script written below to change the 2nd entry in a text file. The text file has the following structure:

#cat myFile.txt
bill:g68hjdh78gh:100:88
harry:bft647hsds:7876:77
... (the list continues)

The script is written as follows:
#cat awk_test.sh
#!/bin/sh
awk < myFile.txt
'BEGIN{
FS = ":"
}
{
split($0, field, ":") #split fields delimited by :
if(field[1] ~ /^bill$/)
{
field[2]=`head -1 pattern`
}
}
END{
print field[1]
print field[2]
}

I executed the script as:
# awk_test.sh
However, the 2nd field was not at all modified with the new value specified from the file "pattern".
#cat pattern
dhsgh777

Also I get an error message for the line
field[2]=`head -1 pattern`, which says:

awk_test.sh: = dhsgh777: command not found

Could someone show me how I could modify the script to solve this error and at the same time modify the 2nd field in the file "myFile.txt" ?

I'm a newbie in AWK scripting.

Thanks
5 REPLIES 5
Robert-Jan Goossens
Honored Contributor

Re: AWK script

Hi,

The second field in the passwd file is encrypted !!!!! it is not possible to change this by replacing this field with awk or sed or wathever filter. Think you have better luck using the command

#passwd user

Robert-Jan.
Robert-Jan Goossens
Honored Contributor
Solution

Re: AWK script

Hi again,

Take look at this link, it will help you.

http://forums.itrc.hp.com/cm/QuestionAnswer/1,,0xce0857bd90a9d611abdb0090277a778c,00.html

Kind regards,

Robert-Jan.
curt larson_1
Honored Contributor

Re: AWK script

the line field[2]=`head -1 pattern` is your problem. The fast fix is probably to put `head -1 pattern` in single quotes ('`head -1 pattern`'), but this isn't good programming practice. A better way is "head -1 pattern" | getline field[2]. And my preference would be to get the value i'm looking to use and pass it into awk using the commandline option -v var=varValue. Along those same lines instead using the BEGIN block just to set the field seperator, use the -F option to do this. And your END block just prints the values of fields one and two for the last line in your file.
Assuming you'd like to print the first two fields for everyline (after your modifications). I'd do something like this:
awk -F: -v var=$(head -1 pattern) < myFile.txt '{
if ( $1 == "bill" ) $2 = var;
printf("%s %s\n",$1,$2);
}'
harry d brown jr
Honored Contributor
Joseph A Benaiah_1
Regular Advisor

Re: AWK script

Try this amendment to your original code:

awk 'BEGIN { FS = ":" }

{ split($0, field, ":")
if ( field[1] ~ /^bill/ )
{
cmd = "head -1 pattern"
cmd | getline output
close(cmd)
field[2] = output
print field[1], field[2]
}
}' myFile.txt

It makes use of one line command substitution using a pipe. If you have the Oreilly Sed and Awk book, this is well documented with good examples.

Cheers,

Joseph