我有以下文件:
$$ head on_this_file.txt
Instance,Session,SenderCompID,Type,SrcAddr,SrcPort,DstAddr,DstPort,Protocol,Client,MIC,curr
304,PBAR29,PBAR29,V,146.127.180.96/27,,162.69.138.157,40008,pillar,DESH,ARCX,USD
336,PBAR29,PBAR29,V,146.127.180.64/28,,162.69.138.157,40008,pillar,DESH,ARCX,USD
304,PBAR36,PBAR36,V,146.127.180.96/27,,162.69.142.4,40015,pillar,DESH,ARCX,USD
336,PBAR36,PBAR36,V,146.127.180.64/28,,162.69.142.4,40015,pillar,DESH,ARCX,USD
304,PBAR28,PBAR28,V,146.127.180.96/27,,162.69.142.109,40007,pillar,DESH,ARCX,USD
336,PBAR28,PBAR28,V,146.127.180.64/28,,162.69.142.109,40007,pillar,DESH,ARCX,USD
310,PBAR88,PBAR88,V,146.127.197.128/26,,162.69.142.207,40285,pillar,SQOL,ARCX,USD
346,PBAR88,PBAR88,V,146.127.168.64/27,,162.69.142.207,40285,pillar,SQOL,ARCX,USD
304,PBAR31,PBAR31,V,146.127.180.96/27,,162.69.138.62,40010,pillar,DESH,ARCX,USD
我正在尝试更改以其他文件上的行开头的所有行:
$$ cat change_these_lines_only.txt
211
304
310
328
342
所以这些行最后会有“;X”。例如第一行:
304,PBAR29,PBAR29,V,146.127.180.96/27,,162.69.138.157,40008,pillar,DESH,ARCX,USD
将会:
304,PBAR29,PBAR29,V,146.127.180.96/27,,162.69.138.157,40008,pillar,DESH,ARCX,USD;X
我尝试过以下命令:
grep -f change_these_lines_only.txt on_this_file.txt | xargs -L1 -I {} sh -c "perl -p -i -e 's/{}\n/{};X\n/' on_this_file.txt"
但它显然不起作用:
Number found where operator expected at -e line 1, near "s/304,PBAR29,PBAR29,V,146.127.180.96/27,,162.69.138.157,40008,pillar,DESH,ARCX,USD\n/304"
Backslash found where operator expected at -e line 1, near "X\"
syntax error at -e line 1, near "s/304,PBAR29,PBAR29,V,146.127.180.96/27,,162.69.138.157,40008,pillar,DESH,ARCX,USD\n/304"
Execution of -e aborted due to compilation errors.
(...)
我尝试过对同一命令进行多次修改,但没有成功。有人能指出我正确的方向吗?万分感谢!
答案1
抱歉,对 Perl 没有太多经验。
for X in $(cat change_this_lines_only.txt)
do
sed -i "/^${X},/s/\$/;X/" on_this_file.txt
done
答案2
使用 awk 但是必须重定向输出到其他一些文件:
这样我们就可以避免for循环和cat命令
$ awk -F"," '
FNR==NR{ a[$1]=$1;next} (FNR==1){print $0;}((NR > 1) && (a[$1]==$1)){ print $0",X"}' change_these_lines_only.txt on_this_file.txt
Instance,Session,SenderCompID,Type,SrcAddr,SrcPort,DstAddr,DstPort,Protocol,Client,MIC,curr
304,PBAR29,PBAR29,V,146.127.180.96/27,,162.69.138.157,40008,pillar,DESH,ARCX,USD,X
304,PBAR36,PBAR36,V,146.127.180.96/27,,162.69.142.4,40015,pillar,DESH,ARCX,USD,X
304,PBAR28,PBAR28,V,146.127.180.96/27,,162.69.142.109,40007,pillar,DESH,ARCX,USD,X
310,PBAR88,PBAR88,V,146.127.197.128/26,,162.69.142.207,40285,pillar,SQOL,ARCX,USD,X
304,PBAR31,PBAR31,V,146.127.180.96/27,,162.69.138.62,40010,pillar,DESH,ARCX,USD,X