Pet*_*Dev 5 bash awk replace sed
我有两个文件,fileA和一个名字列表:
AAAAA
BBBBB
CCCCC
DDDDD
Run Code Online (Sandbox Code Playgroud)
另一个文件B与另一个列表:
111
222
333
444
Run Code Online (Sandbox Code Playgroud)
和第三个带有一些文字的fileC:
Hello AAAAA toto BBBBB dear "AAAAA" trird BBBBBB tuizf AAAAA dfdsf CCCCC
Run Code Online (Sandbox Code Playgroud)
所以我需要通过fileB模式找到并替换fileC中fileA的每个模式.有用 !但我意识到fileC包含像"AAAAA"这样的词,它不会被"111"取代.
我这样做但它似乎不起作用.
#! /bin/bash
while IFS= read -r lineA && IFS= read -r lineB <&3; do
sed -i -e "s/$lineA/$lineB/g" fileC
done <fileA 3<fileB
Run Code Online (Sandbox Code Playgroud)
这是一份很好的工作GNU awk:
$ cat replace.awk
FILENAME=="filea" {
a[FNR]=$0
next
}
FILENAME=="fileb" {
b[a[FNR]]=$0
next
}
{
for (i=1;i<=NF;i++) {
printf "%s%s",(b[$i]?b[$i]:$i),(i==NF?RS:FS)
}
}
Run Code Online (Sandbox Code Playgroud)
演示:
$ awk -f replace.awk filea fileb filec
Hello 111 toto 222 dear 111 trird BBBBBB tuizf 111 dfdsf 333
Run Code Online (Sandbox Code Playgroud)
sehe的解决方案:
FILENAME==ARGV[1] { # Read the first file passed in
find[FNR]=$0 # Create a hash of words to replace
next # Get the next line in the current file
}
FILENAME==ARGV[2] { # Read the second file passed in
replace[find[FNR]]=$0 # Hash find words by the words to replace them
next # Get the next line in the current file
}
{ # Read any other file passed in (i.e third)
for (i=1;i<=NF;i++) { # Loop over all field & do replacement if needed
printf "%s%s",(replace[$i]?replace[$i]:$i),(i==NF?RS:FS)
}
}
Run Code Online (Sandbox Code Playgroud)
对于替换忽略字边界:
$ cat replace.awk
FILENAME==ARGV[1] {
find[FNR]=$0
next
}
FILENAME==ARGV[2] {
replace[find[FNR]]=$0
next
}
{
for (word in find)
gsub(find[word],replace[find[word]])
print
}
Run Code Online (Sandbox Code Playgroud)
演示:
$ awk -f replace.awk filea fileb filec
Hello 111 toto 222 dear "111" trird 222B tuizf 111 dfdsf 333
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |