我在比较同一文件的两列然后根据另一列替换一列的值时遇到问题
例如,我的文件就像:
name col1 col2
abc no no
xyz yes yes
man no no
wrr no no
这里我要检查文件col1中的每个'no'值是否要将col2的值更改为'N / A'
答案 0 :(得分:5)
$ awk '$2=="no"{$3="N/A"}1' file
name col1 col2
abc no N/A
xyz yes yes
man no N/A
wrr no N/A
答案 1 :(得分:0)
使用sed
:
[ ~]$ sed "s/\([A-Za-z]*\ *no\ *\).*/\1N\/A/g" file
name col1 col2
abc no N/A
xyz yes yes
man no N/A
wrr no N/A
使用awk
:
[ ~]$ awk '$2 == "no" {$3="N/A"} {print}' file
name col1 col2
abc no N/A
xyz yes yes
man no N/A
wrr no N/A
您也可以根据需要更改显示:
[ ~]$ awk '$2 == "no" {$3="N/A"} {print $1"\t"$2"\t"$3}' file
[ ~]$ awk '$2 == "no" {$3="N/A"} {print $1" "$2" "$3}' file
# ...
答案 2 :(得分:0)
这是一个awk问题:
cat your-file.txt | awk '{if ( $2 == "no" ) { $3 = "N/A"; } print $0 }' > your-new-file.txt
答案 3 :(得分:0)
这是一个简单的解决方案:
while read name col1 col2 ; do
if[[ "$col" = no ]]; then
echo "$name $col1 N/A"
else
echo "$name $col1 $col2"
fi
done < file
如果您需要更快,请使用此awk
脚本:
$1 == "no" { print $1" "$2" N/A"; next; }
{ print; }