Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 仅当包含字符串的行还包含使用Bash在另一个文件中找到的数字时,如何替换该文件中的字符串?_Linux_Bash_Csv_Awk_Sed - Fatal编程技术网

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

Linux 仅当包含字符串的行还包含使用Bash在另一个文件中找到的数字时,如何替换该文件中的字符串?,linux,bash,csv,awk,sed,Linux,Bash,Csv,Awk,Sed,我想使用Bash将以下file.csv文件中的target的所有实例替换为replace,但前提是包含它的行也包含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.cs

我想使用Bash将以下file.csv文件中的
target
的所有实例替换为
replace
,但前提是包含它的行也包含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

你的想法更相似

awk -F, 'FNR==NR{a[$0]=1;next}a[$1]{$3="replace"}1' OFS="," list.txt file.cvs
这里是和
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|.*|/\\b&\\b/ s/target/replace/|' list.txt 
/\b1\b/ s/target/replace/
/\b3\b/ s/target/replace/

等等……嗯。。很好,你在这个问题上表现出了你的努力。但是您可以先搜索SO,因为您可能会在此处看到类似的问题。否,这将把所有
$3
设置为
替换
。OP只想将
目标
替换为
替换
。我认为这是正确的,请测试一下!不,它似乎输出了与file.csv中相同的数据。生成的输出显示在我的答案中,这与您的预期输出完全相同。当我精确运行您的代码时,我得到:1,abc,target,abc 2,abc,target,abc 3,abc,target,abc我希望看到:1,abc,replace,abc 2,abc,target,abc 3,abc,replace,abc检查文件是否有DOS行结尾。还要确保样本数据与实际数据完全相同。
$ sed 's|.*|/\\b&\\b/ s/target/replace/|' list.txt 
/\b1\b/ s/target/replace/
/\b3\b/ s/target/replace/