I am a newbie and would like some help with the following -
Trying to search fileA for a string similar to -
AS11000022010 30.4 31.7 43.7 53.8 60.5 71.1 75.2 74.7 66.9 56.6 42.7 32.5 53.3
I then want to replace that string with a string from fileB -
AS11000022010 30.92 32.42 44.44 54.30 60.92 71.42 75.55 74.89 67.07 56.72 42.99 32.89 53.71
There are multiple lines of data so it would be every instance of AS1100002.
Thanks in advance
Not sure about using sed for this, but here is a solution using awk:
awk 'NR==FNR { K[$1]=$0; next }
{ if($1 in K) $0=K[$1]; print }' fileB fileA
Or if you only want to search/replace for a given value:
awk -vN=AS11000022010 'NR==FNR { if($1 == N)K[$1]=$0; next }
{ if($1 in K) $0=K[$1]; print }' fileB fileA
Thanks Chubler.
The code
awk -vN=AS11000022010 'NR==FNR { if($1 == N)K[$1]=$0; next }
{ if($1 in K) $0=K[$1]; print }' fileB fileA
will produce one line of variables.
Im still trying to figure out
1) how to return multiple lines of variables. Basically need to figure out how to include a wildcard in the AS110000* using AWK.
2) instead of printing out on the screen - what is the correct code for embedding the output it in a file.
Thanks
For wild card matching use awk ~ operator instead of ==
Not sure what you mean by embedding output, but you can redirect the output of awk to a file with > filename
, like this:
awk -vN=AS110000* 'NR==FNR { if($1 ~ N)K[$1]=$0; next }
{ if($1 in K) $0=K[$1]; print }' fileB fileA > fileC
Thanks for the help. It works perfectly.
While reading through the script I am having trouble figuring out what the 'K' does?
K is used as an associative array here.
Example
root@bt:/tmp# cat file
Linux1 Ubuntu
Linux2 Fedora
Linux3 BackTrack
root@bt:/tmp# awk '{K[$1]=$2} END{ for(i in K){print "Key : "i" & Value : "K} }' file
Key : Linux1 & Value : Ubuntu
Key : Linux2 & Value : Fedora
Key : Linux3 & Value : BackTrack
K[Linux1]=Ubuntu
K[Linux2]=Fedora...
regards,
Ahamed