1847890 Members
1448 Online
104021 Solutions
New Discussion

awk/scripting problem

 
Mathais Kashiri
Occasional Contributor

awk/scripting problem

I have a pseudo passwd file, encrypted with format:

1:rtesd
2:refsdcsd
3:fdcsd

where $2 is to be referenced via $1. This is the passwd update section of a password retrieval utility for all our boxes. I want to replace $2 with user entered value ${newpass}. I have tried using sub() to no avail; could you assist.
5 REPLIES 5
Andreas Voss
Honored Contributor

Re: awk/scripting problem

Hi,

i can no see what you want.
Could you post your awk/script to the forum ?

Regards
RikTytgat
Honored Contributor

Re: awk/scripting problem

Hi,

Suppose you have a file (/tmp/test) with following contents:

1:aaaaaaa
2:bbbbbbb
3:ccccccc

And you would like to change

2:bbbbbbb

to

2:fffffff

you can execute the commands:

$ old=$1
$ new=$newvalue
$ awk -v new="$new" -v old="$old" '{ sub(old, new); print }' /tmp/test

to obtain the output

1:aaaaaaa
2:fffffff
3:ccccccc



Hope this answers your question.

Bye,
Rik
James R. Ferguson
Acclaimed Contributor

Re: awk/scripting problem

Hi:

Another way:

Given your variables $OLDPW and $NEWPW:

# sed "s/$OLDPW/$NEWPW/" /original_file > /replacement_file

# mv /replacement_file /original_file

...JRF...
Mathais Kashiri
Occasional Contributor

Re: awk/scripting problem

Thanks for all the replies but my problem is still not answered. I reference via field $1 and change the contents of field $2. Field number 1 i know, but field number two i do not.
Scott D. Allen
Regular Advisor

Re: awk/scripting problem

I think this is what you're looking for.....

cat file | awk -v a=$userid -v b=$newpass -FS: '{
BEGIN {
userid = a
newpass = b
}
if (/^userid/)
then
{ print $1:newpass }
else
{ print }
}' > newfile

The sub function won't work because it replaces only what it's searching for and you want to replace field $2 while keying on $1. Then, just run this and move the result over after the awk runs.

--Scott

"Sometimes the devil you know is better than the devil you don't know."