linux - sed 的不同选项 - 是否获取重复行

标签 linux shell sed replace duplicates

我想在linux的一个文件中找到一个文本,并用另一个文本替换这个文本。例如,将 B101011938 替换为 B101011939

如果我使用 Command1 (C1),输出中会有重复行:

$ cat file
line1:B101011938
$ sed 's/B101011938/B101011939/p' file
line1:B101011939
line1:B101011939

如果我使用 Command2 (C2),则不会出现重复行:

$ cat file
line1:B101011938
$ sed 's/B101011938/B101011939/g' file
line1:B101011939

我的问题是:这些命令有什么区别?

最佳答案

sed 中的替代命令具有以下签名:

s/REGEX/replacement/flags

已关注 POSIX ,标志的值应为零或多个:

n Substitute for the nth occurrence only of the BRE found within the pattern space.

g Globally substitute for all non-overlapping instances of the BRE rather than just the first one. If both g and n are specified, the results are unspecified.

p Write the pattern space to standard output if a replacement was made.

w wfile Write. Append the pattern space to wfile if a replacement was made. A conforming application shall precede the wfile argument with one or more blanks. If the w flag is not the last flag value given in a concatenation of multiple flag values, the results are undefined.

<小时/>

这意味着,当使用 p 标志时,sed 将输出模式空间(由 s 修改的当前行)。由于 sed 默认情况下已经输出模式空间 - 除非使用 -n 命令行选项 - 这会导致修改后的行在输出中出现两次。

关于linux - sed 的不同选项 - 是否获取重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46721888/

相关文章:

linux - 用户可编辑的回显文本

sed - 从另一个文件中的文本文件中删除行

linux - 在任何手机上查看存储在 Linux PC 上的网站

c - 'c interfaces and implementations' (David Hanson) 代码安装

linux - 命令替换问题(变量为空)

c - 如何通过线程将数组作为返回值传递?

android - 我的 shell 脚本没有在 android 上运行

linux - 在shell脚本中的远程ssh命令中传递变量

linux - 在正则表达式之后更改一行的一部分

linux - CentOS 使用 sed 不工作后插入新的文本行