开发者

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

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

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 开发者_如何学Gounix shell tool?


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.


You can use tr:

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

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

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


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

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


With sed:

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

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

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


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

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


No need for Perl here!

# 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜