2

I am trying to remove every character in a text string except for the remaining 11 characters. 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.

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.

OS is macOS High Sierra 10.13.6 and bash version is 3.2.57(1)-release

leetbacoon
  • 869
  • 2
  • 6
  • 23

5 Answers5

5

You can use this sed with a capture group:

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

-pe_-l4_mBY
anubhava
  • 713,503
  • 59
  • 514
  • 593
3

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. ( 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.

$ cat food | sed -E 's/^.*(.{3})$/\1/'
mBY
chepner
  • 446,329
  • 63
  • 468
  • 610
2

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. (See also useless use of cat.)

tripleee
  • 158,107
  • 27
  • 234
  • 292
1

You can use tail or 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
ctac_
  • 2,388
  • 2
  • 6
  • 17
-1

also with rev/cut/rev

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

pqrstuvwxyz

man rev => rev - reverse lines characterwise

hoijui
  • 3,321
  • 1
  • 31
  • 39
karakfa
  • 64,710
  • 7
  • 38
  • 55