bash Sed 和美元符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31370580/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:20:03  来源:igfitidea点击:

Sed and dollar sign

bashsedescaping

提问by threaz

"The Unix Programming Environment" states that '$' used in regular expression in sed means end-of-the line which is fine for me, because

“Unix 编程环境”指出 sed 中正则表达式中使用的“$”表示行尾,这对我来说很好,因为

cat file | sed 's/$/\n/'

is interpretted as "add newline at the end of each line".

被解释为“在每行末尾添加换行符”。

The question arises, when I try to use the command:

问题出现了,当我尝试使用命令时:

cat file | sed '$d'

Shouldn't this line remove each line instead of the last one? In this context, dollar sign means end of the LAST line. What am I getting wrong?

这行不应该删除每一行而不是最后一行吗?在这种情况下,美元符号意味着最后一行的结束。我怎么了?

回答by 200_success

In the second usage, there is no regular expression. The $there is an address, meaning the last line.

在第二种用法中,没有正则表达式。该$有一个地址,这意味着最后一行。

回答by anubhava

$is treated as regex anchor when used in pattern in scommand e.g.

$当在s命令中的模式中使用时,被视为正则表达式锚点,例如

s/$/\n

However in $d, $is nota regex anchor, it is address notation that means the last lineof the input, which is deleted using the dcommand.

然而,在$d$正则表达式锚,它是地址表示法装置的最后一行的输入,这是使用已删除的d命令。

Also note that catis unnecessary in your last command. It can be used as:

另请注意,这cat在您的最后一个命令中是不必要的。它可以用作:

sed '$d' file

回答by Avinash Raj

Note that regexin sed must be inside the delimiters(;,:, ~, etc) other than quotes.

需要注意的是regex在sed必须是分隔符(内;:~,等)比其他报价。

/regex/

ex:

前任:

sed '/foo/s/bar/bux/g' file

or

或者

~regex~

ex:

前任:

sed 's~dd~s~' file

but not 'regex'. So $in '$d'won't be considered as regex by sed. '$d'acts like an address which points out the last line.

但不是'regex'。所以$in'$d'不会被 sed 视为正则表达式。'$d'就像一个地址,指出最后一行。