简体   繁体   English

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

[英]sed: remove all characters except for last n characters

I am trying to remove every character in a text string except for the remaining 11 characters.我试图删除文本字符串中除剩余 11 个字符之外的每个字符。 The string is Sample Text_that-would$normally~be,here--pe_-l4_mBY and what I want to end up with is just -pe_-l4_mBY .字符串是Sample Text_that-would$normally~be,here--pe_-l4_mBY ,我想要结束的只是-pe_-l4_mBY

Here's what I've tried:这是我尝试过的:

$ 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

Please note that the text string isn't really stored in a file, I just used cat food as an example.请注意,文本字符串并没有真正存储在文件中,我只是以cat food为例。

OS is macOS High Sierra 10.13.6 and bash version is 3.2.57(1)-release操作系统为 macOS High Sierra 10.13.6, bash版本为 3.2.57(1)-release

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

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

-pe_-l4_mBY

Basic regular expressions (used by default by sed ) require both the parentheses in the capture group and the braces in the brace expression to be escaped.基本正则表达式(默认情况下由sed )需要捕获组中的括号和大括号表达式中的大括号进行转义。 ( and { are otherwise treated as literal characters to be matched. ({否则被视为要匹配的文字字符。

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

By contrast, explicitly requesting sed to use extended regular expressions with the -E option reverses the meaning, with \\( and \\{ being the literal characters.相比之下,明确要求sed使用带有-E选项的扩展正则表达式会颠倒含义, \\(\\{是文字字符。

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

Try this also:也试试这个:

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

grep , like sed , accepts an arbitrary number of file name arguments, so there is no need for a separate cat . grepsed一样,接受任意数量的文件名参数,因此不需要单独的cat (See alsouseless use of cat .) (另请参阅cat无用用法。)

You can use tail or Parameter Expansion :您可以使用 tail 或 Parameter Expansion :

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

also with rev/cut/rev也带有rev/cut/rev

$ echo abcdefghijklmnopqrstuvwxyz | rev | cut -c1-11 | rev 

pqrstuvwxyz

man rev => rev - reverse lines characterwise man rev => rev - reverse lines characterwise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM