使用Sed交换两个字符串

时间:2018-01-19 15:21:28

标签: linux shell unix awk sed

我有一个文件,我试图更改两个字符串或尝试互相交换..

cat filename| grep m07

filesystem special="/abc/ca97" raw="/abc/ca97" directory="/mount/m07" 
filesystem special="/abc/d1107" raw="/abc/d1107" directory="/m07"

所以我试图用/ m07交换/ mount / m07,以便在操作后输出所需的输出:

  

filesystem special =“/ abc / ca97”raw =“/ abc / ca97”directory =“/ m07”
  filesystem special =“/ abc / d1107”raw =“/ abc / d1107”   目录= “/安装/ M07”

我尝试使用sed ..

sed -e 's/"\/mount\/m07/"\m07/g' -e 's/"\/m07/"\/mount/\/m07' file_name

sed -e 's/"\/m07/"\/mount/\/m07' -e 's/"\/mount\/m07/"\m07/g' file_name

但是在两种情况下它都替换了两个字符串,所以要么在两行中得到/ mount / m07或/ m07 ......

请你建议达到预期输出的路径......

3 个答案:

答案 0 :(得分:4)

简单sed将为您完成任务。

sed '/m07/s#/mount/m07#/m07#;t;/m07/s#/m07#/mount/m07#'    Input_file

对于您提到的Input_file或命令的输出,以下是输出:

your_command | sed '/m07/s#/mount/m07#/m07#;n;/m07/s#/m07#/mount/m07#' 
<filesystem special="/abc/ca97" raw="/abc/ca97" directory="/m07" >
<filesystem special="/abc/d1107" raw="/abc/d1107" directory="/m07">

编辑:现在为上述命令添加说明,感谢Sundeep让我知道t选项优于n。以下代码仅用于解释目的,而不是用于运行。

sed '/m07/                    Searching for string m07 in a line, if it is present then only do substitutions in that line.
s#/mount/m07#/m07#;           Doing substitution here substitute /mount/m07 with m07 here
t;                            t is for(from man sed page) If  a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label if label is omitted, branch to end of script.
/m07/s#/m07#/mount/m07#       searching string m07 and then substitute string /m07 with /mount/m07
'    Input_file               Mentioning Input_file.

答案 1 :(得分:2)

问题被标记为<button id="elem" data-mynum="3"> hello</button> var elem = document.getElementById('elem'); elem.addEventListener("click", clickHandler); function clickHandler(e) { console.log(e.currentTarget.dataset.mynum); } ,因此我假设linux可用(不确定以下解决方案是否为POSIX)。还假设两个字符串不在同一行

GNU sed
  • $ sed 's#/mount/m07#/m07#; t; s#/m07#/mount/m07#' ip.txt filesystem special="/abc/ca97" raw="/abc/ca97" directory="/m07" filesystem special="/abc/d1107" raw="/abc/d1107" directory="/mount/m07" 命令将在成功替换时分支到指定的标签
  • 没有标签,t将跳过其余命令并开始下一个周期
  • 所以,如果t成功,s#/mount/m07#/m07#命令将告诉t跳过其余命令并读取下一行进行处理
  • 但如果第一次替换没有成功,那么将尝试第二次替换

对于非GNU版本 - 感谢@anubhava

sed

进一步阅读

答案 2 :(得分:0)

$ cat sedswap.txt 
/mount/m07
/m07

$ sed -e 's/\/mount\/m07/\/rm07/g' -e 's/\/m07/\/mount\/m07/g' -e 's/\/rm07/\/m07/g' sedswap.txt
/m07
/mount/m07

基本上使用临时变量方法