What does \0 mean in sed?

南笙酒味 提交于 2020-07-08 20:45:08

问题


I have the following code:

echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/\1/p"

It prints 12 as expected, since \1 refers to the first capturing group.

However, if \0 is used instead of \1, the output is 12. Chapter Name, the entire input string is printed.

It seems that as long as the regex found a match, \0 prints the entire input string. Is this correct?

I'm running Debian 10.2.


回答1:


The \0 is a placeholder for the whole match value.

Note that capturing group indices start with 1 and go up until 9 in POSIX regex patterns. The zeroth group is the whole match.

Also, instead of \0, it is more common - and probably more portable - to use & in sed.

echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/\0/p"

is equal to

echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/&/p"

You may read more about & at Using & as the matched string.



来源:https://stackoverflow.com/questions/62123031/what-does-0-mean-in-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!