sed - 在2个字符串之间查找文本并将其用于替换

时间:2013-07-26 07:33:50

标签: unix replace sed awk

我有一个包含许多行的文件,如下所示:

townValue.put("Aachen");    
townValue.put("Aalen");             
townValue.put("Ahlen");             
townValue.put("Arnsberg");          
townValue.put("Aschaffenburg");         
townValue.put("Augsburg");

我想将此行更改为:

townValue.put("Aalen", "Aalen");            
townValue.put("Ahlen", "Ahlen");            
townValue.put("Arnsberg", "Arnsberg");          
townValue.put("Aschaffenburg", "Aschaffenburg");        
townValue.put("Augsburg", "Augsburg");

如何使用sed或awk实现此目的。这似乎是一个特殊的发现和替换任务,我在网上找不到。

感谢您的帮助

2 个答案:

答案 0 :(得分:6)

使用sed -e 's/"[^"]*"/&, &/'

$ cat 1
townValue.put("Aachen");    
townValue.put("Aalen");             
townValue.put("Ahlen");             
townValue.put("Arnsberg");          
townValue.put("Aschaffenburg");         
townValue.put("Augsburg");
$ sed -e 's/"[^"]*"/&, &/' 1
townValue.put("Aachen", "Aachen");    
townValue.put("Aalen", "Aalen");             
townValue.put("Ahlen", "Ahlen");             
townValue.put("Arnsberg", "Arnsberg");          
townValue.put("Aschaffenburg", "Aschaffenburg");         
townValue.put("Augsburg", "Augsburg");

根据sed(1):

  

S /的regexp /更换/

     

尝试将regexp与模式空间匹配。如果成功,请替换与替换匹配的部分。替换可以包含特殊字符& 来引用匹配的模式空间的那部分,并且特殊转义\ 1到\ 9以引用正则表达式中相应的匹配子表达式。

答案 1 :(得分:1)

的代码,因为命令行中有大量引号我建议使用脚本:

awk -f script file
  • 脚本

    BEGIN {FS=OFS="\""}
    $3=", \""$2"\""$3
    

$ cat file
townValue.put("Aachen");
townValue.put("Aalen");
townValue.put("Ahlen");
townValue.put("Arnsberg");
townValue.put("Aschaffenburg");
townValue.put("Augsburg");

$ awk -f script file
townValue.put("Aachen", "Aachen");
townValue.put("Aalen", "Aalen");
townValue.put("Ahlen", "Ahlen");
townValue.put("Arnsberg", "Arnsberg");
townValue.put("Aschaffenburg", "Aschaffenburg");
townValue.put("Augsburg", "Augsburg");