我想在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/