bash 'G' 用 sed 命令做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29435598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does 'G' do with sed command?
提问by Scott Pearce
I have tried two different sed commands against a text file called "file1.txt". I have received the same result or output. What I don't understand is the meaning or use of "G" option! I have searched online, but I couldn't find a good answer!
我已经针对名为“file1.txt”的文本文件尝试了两种不同的 sed 命令。我收到了相同的结果或输出。我不明白的是“G”选项的含义或用法!我在网上搜索过,但找不到好的答案!
Here are two commands:
这里有两个命令:
sed 'G' file1.txt
sed '/^$/d;G' file.txt
Both commands give the same output! They create a one line gap between each line in the text file! I know that'^$' refers to line containing nothing, but what does 'G' do. For example if I put 'd' instead of 'G' all blank lines will be deleted!
两个命令给出相同的输出!它们在文本文件中的每一行之间创建一行空白!我知道 '^$' 是指不包含任何内容的行,但是 'G' 有什么作用。例如,如果我输入 'd' 而不是 'G',所有空行都将被删除!
采纳答案by Tom Ruh
According to the sed man
根据 sed man
g
Replace the contents of the pattern space with the contents of the hold space.
用保持空间的内容替换模式空间的内容。
G
Append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space.
将换行符附加到模式空间的内容,然后将保持空间的内容附加到模式空间的内容。
回答by Etan Reisner
Instead of exchanging the hold space with the pattern space, you can copy the hold space to the pattern space with the "g" command. This deletes the pattern space. If you want to append to the pattern space, use the "G" command. This adds a new line to the pattern space, and copies the hold space after the new line.
您可以使用“g”命令将保持空间复制到模式空间,而不是用模式空间交换保持空间。这将删除模式空间。如果要附加到模式空间,请使用“G”命令。这将向模式空间添加一个新行,并在新行之后复制保持空间。
That is, instead of swapping the current contents of the hold and pattern space (current line, etc) you can take the pattern space and copy it into the hold space (either replacing or appending to the hold space in the process).
也就是说,不是交换保持和模式空间的当前内容(当前行等),您可以获取模式空间并将其复制到保持空间(在进程中替换或附加到保持空间)。
Those two sed commands are among the idiomatic sed one-liners that you can find onlineand they do the same thing only for certain files (those without blank lines in them).
这两个 sed 命令是您可以在网上找到的惯用 sed one-liners 之一,它们仅对某些文件(其中没有空行的文件)执行相同的操作。
# double space a file
sed G
# double space a file which already has blank lines in it. Output file
# should contain no more than one blank line between lines of text.
sed '/^$/d;G'