Файл 1 CAT
ABC,23
DFG,45
Ghj,678
CAT File2
Listed LinkedIn yellow ABC
Fixed DFG linked ABC
Holiday Europe Ghj DFG
Мне нужен вывод как ниже
Listed LinkedIn yellow 23
Fixed 45 linked 23
Holiday Europe 678 45
Можно сделать это использование 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
Преобразовать file1
в команды для sed
и использовать их для изменения file2
:
sed -r 's/(.*),(.*)/s,\1,\2,/' file1 | sed -f - file2
Это предполагает, что значения в file1
не содержат специальных символов, и вы хотите заменить все вхождения в file2
.
Вы могли использовать 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