1756328 Members
3324 Online
108846 Solutions
New Discussion юеВ

Awk with sub

 
SOLVED
Go to solution
Chris Frangandonis
Regular Advisor

Awk with sub

Hi all

I have a file thats looks like this

111 222 0000 9999 RABC:AB fat 1 3 5
111 223 0000 9999 RABC:AC cat 1 34 5

What I would like to do is sub(0000,XXXX && sub(9999,XXXX) when awk {if($5 == "???:A[A-Z]")
How can I put this in the awk statement.

Thanks in advanced
Chris
8 REPLIES 8
Ceesjan van Hattum
Esteemed Contributor

Re: Awk with sub

Can you please a little more clear? Your first sub has no ')', and your awk has a ??? but shouldn't it have ???? (4 char's) ??
Please just give us some input and output, then we will write you the blackbox.

Regards,
Ceesjan
Chris Frangandonis
Regular Advisor

Re: Awk with sub

Hi Ceesja,

Search in the file, and when a pattern RABC:AC is found for eg RABC:AB or RABC:AC or ????:A[A-Z] is found, then sub 0000 99999 to XXXX for 0000 and XXXX for 9999. The result should look like this

111 222 XXXX XXXX RABC:AB fat 1 3 5
111 223 XXXX XXXX RABC:AC cat 1 34 5

Thanks Once again
Chris
Rodney Hills
Honored Contributor

Re: Awk with sub

Chris,

Try this awk command-

awk '$5~/....:A[A-Z]/{$3="XXXX"; $4="XXXX" ; print $0}' yourinputfile.txt

-- Rod Hills
There be dragons...
Ceesjan van Hattum
Esteemed Contributor

Re: Awk with sub

What about this:

awk '{
sub(/0000/,"XXXX");
sub(/9999/,"XXXX");
print
}' input

Regards,
Ceesjan
Rodney Hills
Honored Contributor
Solution

Re: Awk with sub

My first awk script assumed only lines with ....:A[A-Z] would be substituted and printed.

Here is another version, that prints all lines, but only changes those lines that match the pattern.

awk '$5~/....:A[A-Z]/{$3="XXXX"; $4="XXXX"};{print $0}' yourinputfile.txt

Hope this helps...

-- Rod Hills
There be dragons...
Chris Frangandonis
Regular Advisor

Re: Awk with sub

Hi Rod,

Great stuff. I tried this one with results which is incorrect. Could you PLEASE explain why.

cat FILE | awk -v var="[0-9][0-9][0-9][0-9]" -v var2="XXXX" '{if ($5 == "....:A[A-Z]");{sub(var1,var2,$3)};{print $0}}' | more

Many Thanks to All
Chris
Rodney Hills
Honored Contributor

Re: Awk with sub

Chris,

In your sample you set "var=". Did you mean var1= ?

You are also doing a comparsion using "$5 ==", this should be "$5 ~" so that it does a regular expression compare.

The regular expression I believe needs to be enclosed with "/".

Remove the ";" after the if ($5 ... ).

Try this-

cat FILE | awk -v var1="[0-9][0-9][0-9][0-9]" -v var2="XXXX" '{if ($5 ~ /....:A[A-Z]/){sub(var1,var2,$3)};{print $0}}' | more

Hope this Helps.

-- Rod Hills

There be dragons...
Chris Frangandonis
Regular Advisor

Re: Awk with sub

Hi Rod,

Thanks for all you help, it was greatly appreciated.

Chris