bash – 通过fileB模式在fileC中查找和替换fileA的模式
发布时间:2020-12-15 21:47:36 所属栏目:安全 来源:网络整理
导读:我有两个文件,fileA和一个名字列表: AAAAA BBBBBCCCCCDDDDD 另一个文件B与另一个列表: 111 222333444 和第三个带有一些文字的fileC: Hello AAAAA toto BBBBB dear "AAAAA" trird BBBBBB tuizf AAAAA dfdsf CCCCC 所以我需要通过fileB模式找到并替换fileC
我有两个文件,fileA和一个名字列表:
AAAAA BBBBB CCCCC DDDDD 另一个文件B与另一个列表: 111 222 333 444 和第三个带有一些文字的fileC: Hello AAAAA toto BBBBB dear "AAAAA" trird BBBBBB tuizf AAAAA dfdsf CCCCC 所以我需要通过fileB模式找到并替换fileC中fileA的每个模式. 我这样做但它似乎不起作用. #! /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 解决方法
这对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) } } 演示: $awk -f replace.awk filea fileb filec Hello 111 toto 222 dear 111 trird BBBBBB tuizf 111 dfdsf 333 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) } } 对于替换,忽略单词边界: $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 } 演示: $awk -f replace.awk filea fileb filec Hello 111 toto 222 dear "111" trird 222B tuizf 111 dfdsf 333 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |