Linux 如何使用 sed 替换退格字符 (\b)?

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

How do I replace backspace characters (\b) using sed?

linuxbashshellsed

提问by Thiago de Arruda

I want to delete a fixed number of some backspace characters ocurrences ( \b ) from stdin. So far I have tried this:

我想从标准输入中删除固定数量的退格字符( \b )。到目前为止,我已经尝试过这个:

echo -e "1234\b\b\b56" | sed 's/\b{3}//'

But it doesn't work. How can I achieve this using sed or some other unix shell tool?

但它不起作用。如何使用 sed 或其他一些 unix shell 工具来实现这一点?

采纳答案by mkb

sed interprets \bas a word boundary. I got this to work in perl like so:

sed 解释\b为单词边界。我让它在 perl 中工作,如下所示:

echo -e "1234\b\b\b56" | perl -pe '$b="\b";s/$b//g'

回答by Eugene Yarmash

You can use tr:

您可以使用tr

echo -e "1234\b\b\b56" | tr -d '\b'
123456

If you want to delete three consecutive backspaces, you can use Perl:

如果要删除三个连续的退格,可以使用Perl:

echo -e "1234\b\b\b56" | perl -pe 's/(0){3}//'

回答by wkl

With sed:

使用 sed:

echo "123\b\b\b5" | sed 's/[\b]\{3\}//g'

echo "123\b\b\b5" | sed 's/[\b]\{3\}//g'

You have to escape the {and }in the {3}, and also treat the \bspecial by using a character class.

你必须逃脱{,并}{3},而且治疗\b通过使用字符类特殊。

[birryree@lilun ~]$ echo "123\b\b\b5" | sed 's/[\b]\{3\}//g'
1235

回答by Jon Nalley

You can use the hexadecimal value for backspace:

您可以使用十六进制值作为退格键:

echo -e "1234\b\b\b56" | sed 's/\x08\{3\}//'

You also need to escape the braces.

您还需要转义大括号。

回答by pixelbeat

Note if you want to remove the characters being deleted also, have a look at ansi2html.shwhich contains processing like:

请注意,如果您还想删除被删除的字符,请查看ansi2html.sh,其中包含如下处理:

printf "12..\b\b34\n" | sed ':s; s#[^\x08]\x08##g; t s'

回答by gutti

No need for Perl here!

这里不需要 Perl!

# version 1
echo -e "1234\b\b\b56" | sed $'s/\b\{3\}//' | od -c

# version 2
bvar="$(printf '%b' '\b')"
echo -e "1234\b\b\b56" | sed 's/'${bvar}'\{3\}//' | od -c