Reputation: 321
I have a simple file like :
a 123
b 234
In a second file, I want to replace a string by the value corresponding to a -> "123" in a single command.
Is there a way to pipe the result of grep "a" file1 | awk {print $2}
to sed s/string/my_output/g file2
Upvotes: 2
Views: 6428
Reputation: 41446
Here is an awk
cat file1
a 123
b 234
cat file2
cat
bad hat
awk -v FS="" 'FNR==NR {split($0,b," ");a[b[1]]=b[2];next} {for (i=1;i<=NF;i++) $i=a[$i]?a[$i]:$i}1' file1 file2
c 123 t
234 123 d h 123 t
How does it work.
awk -v FS="" ' # By setting Field Separator to nothing, it works on one and one letter
FNR==NR { # This is true only for the first file (file1)
split($0,arr-b," ") # Split the data in first file (arr-b[1]=first filed, eks a, arr-b[2]=second field, eks 123
arr-a[arr-b[1]]=arr-b[2] # Store this to an array using field 1 as index. arr-a[a]=123 arr-a[b]=234 etc
next} # Skip to next record in file1
{ # Run this for file2
for (i=1;i<=NF;i++) # Loop trough on by on letter "c" "a" "t"
$i=arr-a[$i]?arr-a[$i]:$i} # Test the letter one by one if its found in array "arr-a", if so use data from array, if not keep value
1 # Since this always will be true, do default action "print $0" (print every line)
' file1 file2 # Read file1 and file2
Upvotes: 1
Reputation: 15160
here's a pure-Awk solution. Put the dictionary in 'adict.dat' then pass your input file to the Awk command
BEGIN {
while(( getline line < "adict.dat" ) > 0 ) {
$0 = line;
myvars[$1] = $2;
}
}
{
for (varname in myvars) {
gsub(varname, myvars[varname]);
}
print;
}
/bin/echo 'a x b y' | gawk -f arepl.awk
123 x 234 y
Upvotes: 0
Reputation: 818
You could do the following:
grep a file1| awk '{print $2}' > tmp.txt
This will put '123' in a temporary file. Then:
sed -f script.sed file2
Where the contents of script.sed is
/string to replace/ {
r tmp.txt
d
}
This script replaces "string to replace" with the contents of tmp.txt.
Upvotes: 0
Reputation: 37258
If I interpret your question correctly, try
sed 's@^\(.*\) \(.*\)$@s/\1/\2/g@' SimpleFile > substitutions.file
sed -f substitutions.file 2ndFile > 2ndFile.tmp && mv 2ndFile.tmp 2ndFile
The first step will create a sed substitions file like
s/a/123/g
s/b/234/g
which when used as in line2 above, will substitute each a with 123, etc.
IHTH
Upvotes: 0