sed:删除除最后n个字符外的所有字符

问题描述 投票:2回答:5

我正在尝试删除文本字符串中除其余11个字符之外的所有字符。字符串是Sample Text_that-would$normally~be,here--pe_-l4_mBY,我想结束的只是-pe_-l4_mBY

这是我尝试过的:

$ cat food
Sample Text_that-would$normally~be,here--pe_-l4_mBY
$ cat food | sed 's/^.*(.{3})$/\1/'
sed: 1: "s/^.*(.{3})$/\1/": \1 not defined in the RE

[请注意,文本字符串并没有真正存储在文件中,我只是以cat food为例。

OS是macOS High Sierra 10.13.6,并且bash版本是3.2.57(1)-发布

bash macos unix sed text-processing
5个回答
4
投票

您可以将此sed与捕获组一起使用:

sed -E 's/.*(.{11})$/\1/' file

-pe_-l4_mBY

3
投票

基本正则表达式(默认为sed使用)要求捕获组中的括号和大括号表达式中的大括号都必须转义。 ({否则被视为要匹配的文字字符。

$ cat food | sed 's/^.*\(.\{3\}\)$/\1/'
mBY

相反,明确地要求sed使用带有-E选项的扩展正则表达式会颠倒含义,\(\{是文字字符。

$ cat food | sed -E 's/^.*(.{3})$/\1/'
mBY

2
投票

也请尝试:

grep -o -E '.{11}$' food

grepsed一样,接受任意数量的文件名参数,因此不需要单独的cat。 (另请参见useless use of cat.)


1
投票

您可以使用tail或Parameter Expansion:

cat

-1
投票

也使用string='Sample Text_that-would$normally~be,here--pe_-l4_mBY' echo "$string" | tail -c 11 echo "${string#${string%??????????}}" pe_-l4_mBY pe_-l4_mBY

rev/cut/rev

$ echo abcdefghijklmnopqrstuvwxyz | rev | cut -c1-11 | rev pqrstuvwxyz => man rev

© www.soinside.com 2019 - 2024. All rights reserved.