简体   繁体   English

使用awk或sed在文件中动态替换字符串

[英]use awk or sed to replace string dynamically in file

I have a need to replace filename in a file to a string which is cp command and hence it should replace existing filename with cp source destination in same file .file is comma separated #m sample file 我需要将文件中的文件名替换为cp命令的字符串,因此它应该用同一文件中的cp源目标替换现有文件名。文件是逗号分隔的#m示例文件

ABC,TS-R:56:UT-123,/apps/home/t.txt
ICA,Y6734YGSU,/apps/home/t2.txt
MDI,UI-HDGD-PO567,/apps/home/t3.txt

now i want a sed or awk command which can replace the /apps/home/<filename>.txt to cp /apps/home/<filename>.txt /apps/cmb/<filename>.txt 现在我想要一个sed或awk命令,它可以将/ /apps/home/<filename>.txt cp /apps/home/<filename>.txt /apps/cmb/<filename>.txt替换为cp /apps/home/<filename>.txt /apps/cmb/<filename>.txt

so after sed/awk same file should have contents 所以在sed / awk之后,同一个文件应该包含内容

ABC,TS-R:56:UT-123,cp /apps/home/t.txt /apps/cmb/t.txt
ICA,Y6734YGSU,cp /apps/home/t2.txt /apps/cmb/t2.txt
MDI,UI-HDGD-PO567,cp /apps/home/t3.txt /apps/cmb/t3.txt

I tried awk -F, '{$3="cp "$3" "$3""}1' OFS=, test.txt but its just printing ABC,TS-R:56:UT-123,cp /apps/home/t.txt /apps/home/t.txt also in console and not changing in file. 我尝试了awk -F, '{$3="cp "$3" "$3""}1' OFS=, test.txt但它仅打印ABC,TS-R:56:UT-123,cp /apps/home/t.txt /apps/home/t.txt也可以在控制台中ABC,TS-R:56:UT-123,cp /apps/home/t.txt /apps/home/t.txt ,并且不更改文件。

Thanks in advance . 提前致谢 。

This should do: 应该这样做:

awk -F/ '{print $1"cp ",$2,$3,$4 " ",$2,"cmb",$4}' OFS=/ file
ABC,TS-R:56:UT-123,cp /apps/home/t.txt /apps/cmb/t.txt
ICA,Y6734YGSU,cp /apps/home/t2.txt /apps/cmb/t2.txt
MDI,UI-HDGD-PO567,cp /apps/home/t3.txt /apps/cmb/t3.txt

You can use awk: 您可以使用awk:

awk -F, -v OFS=, '{p=$NF; sub(/\/home\//, "/cmb/", $NF); 
     $NF=sprintf("cp %s %s", p, $NF)} 1' file
ABC,TS-R:56:UT-123,cp /apps/home/t.txt /apps/cmb/t.txt
ICA,Y6734YGSU,cp /apps/home/t2.txt /apps/cmb/t2.txt
MDI,UI-HDGD-PO567,cp /apps/home/t3.txt /apps/cmb/t3.txt

Since this is simple substitutions on individual lines it'd be an appropriate job for sed: 由于这是在单行上的简单替换,因此对sed来说是一项适当的工作:

$ sed -r 's:(/[^/]+/)([^/]+)(/[^/]+):cp & \1cmb\3:' file
ABC,TS-R:56:UT-123,cp /apps/home/t.txt /apps/cmb/t.txt
ICA,Y6734YGSU,cp /apps/home/t2.txt /apps/cmb/t2.txt
MDI,UI-HDGD-PO567,cp /apps/home/t3.txt /apps/cmb/t3.txt

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

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