gpt4 book ai didi

linux - 使用 Sed 交换两个字符串

转载 作者:太空狗 更新时间:2023-10-29 11:31:14 27 4
gpt4 key购买 nike

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

cat filename| grep m07

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

所以我正在尝试将/mount/m07 与/m07 交换,以便所需的输出应该在操作之后:

filesystem special="/abc/ca97" raw="/abc/ca97" directory="/m07"
filesystem special="/abc/d1107" raw="/abc/d1107" directory="/mount/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...

您能否建议达到所需输出的路径...

最佳答案

简单的 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.

关于linux - 使用 Sed 交换两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48344296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com