繁体   English   中英

仅当包含它的行还包含使用Bash在另一个文件中找到的数字时,如何替换文件中的字符串?

[英]How to replace a string in a file only if the line containing it also contains a number found in another file using Bash?

我想使用Bash replace以下file.csv中的所有target实例,但仅当包含它的行还包含list.txt中找到的数字时:

FILE.CSV:

1,abc,target,abc
2,abc,target,abc
3,abc,target,abc

LIST.TXT:

1
3

期望的输出:

1,abc,replace,abc
2,abc,target,abc
3,abc,replace,abc

我试图使用sed

sed 's/target/replace' file.csv > newfile.csv

如何在list.txt中包含检查每一行的逻辑?

这是一个更适合awk

awk 'BEGIN { FS=OFS="," }       # set input/output field delimiter to comma
   FNR == NR {                  # for 1st file in the arguments i.e. list.txt
      a[$1]                     # store each value of $1 in an array a
      next                      # move to next record
}
$1 in a {                       # for 1st file in the arguments i.e. file.csv
   sub(/target/, "replace", $3) # replace target by replace in 3rd column
} 1' list.txt file.csv          # print each record from 2nd file

1,abc,replace,abc
2,abc,target,abc
3,abc,replace,abc

代码演示

这是一个流程替换sed的混搭。

使用sed生成sed命令

$ sed 's|.*|/&/ s/target/replace/|' list.txt
/1/ s/target/replace/
/3/ s/target/replace/

使用sed输出作为脚本文件

$ sed -f <(sed 's|.*|/&/ s/target/replace/|' list.txt) file.csv 
1,abc,replace,abc
2,abc,target,abc
3,abc,replace,abc


要仅在文件开头匹配,请使用

$ sed 's|.*|/^&/ s/target/replace/|' list.txt 
/^1/ s/target/replace/
/^3/ s/target/replace/

或者使用单词边界限制模式:

$ sed 's|.*|/\\b&\\b/ s/target/replace/|' list.txt 
/\b1\b/ s/target/replace/
/\b3\b/ s/target/replace/

等等...

想法与你同情!

awk -F, 'FNR==NR{a[$0]=1;next}a[$1]{$3="replace"}1' OFS="," list.txt file.cvs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM