猫档案 1
ABC,23
DFG,45
Ghj,678
猫文件2
Listed LinkedIn yellow ABC
Fixed DFG linked ABC
Holiday Europe Ghj DFG
我需要如下输出
Listed LinkedIn yellow 23
Fixed 45 linked 23
Holiday Europe 678 45
答案1
转换file1
成的命令sed
并使用它们来修改file2
:
sed -r 's/(.*),(.*)/s,\1,\2,/' file1 | sed -f - file2
这假设中的值file1
不包含特殊字符,并且您想要替换中的所有出现file2
。
答案2
您可以使用bash
关联数组来实现这一点。
$ cat foo.txt # Contents of "foo.txt"
ABC,23
DFG,45
Ghj,678
$ cat bar.txt # Contents of "bar.txt"
Listed LinkedIn yellow ABC
Fixed DFG linked ABC
Holiday Europe Ghj DFG
$ declare -A foobar # Declaring associative array "foobar"
## Putting comma separated portions of file "foo.txt" as key-value
## pair for array "foobar"
$ while IFS=',' read a b; do foobar["$a"]="$b"; done <foo.txt
## Now reading each line of "bar.txt" and iterating over the keys
## of array "foobar" by "${!foobar[@]}" to find a match, if found
## correspoding value of the key will replace the key using parameter
## expansion pattern "${line//key/value}"
$ while IFS=' ' read line; do for i in "${!foobar[@]}"; do \
line="${line//"$i"/"${foobar["$i"]}"}"; done; echo "$line"; done <bar.txt
Listed LinkedIn yellow 23
Fixed 45 linked 23
Holiday Europe 678 45
以下是最后一部分的扩展版本:
while IFS=' ' read line; do
for i in "${!foobar[@]}"; do
line="${line//"$i"/"${foobar["$i"]}"}"
done
echo "$line"
done <bar.txt
答案3
你可以使用awk
awk 'FS="," {\
if(NR == FNR) {\
n[(FNR"")] = $0\
} else {\
a[($1)] = $2\
}\
}\
END {\
for (i in n) {\
for (j in a) {\
gsub(j,a[j],n[i])\
}\
print n[i]\
}\
}' File2 File1
例子
输入文件
cat foo
ABC,23
DFG,45
Ghj,678
cat bar
Listed LinkedIn yellow ABC
Fixed DFG linked ABC
Holiday Europe Ghj DFG
命令和输出
% awk 'FS="," { if(NR == FNR) {n[(FNR"")] = $0} else {a[($1)] = $2}} END {for (i in n) {for (j in a) {gsub(j,a[j],n[i])} print n[i]}}' bar foo
Listed LinkedIn yellow 23
Fixed 45 linked 23
Holiday Europe 678 45