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
  • 1,111
  • 2
  • 9
  • 32

5 Answers5

5

You can use this sed with a capture group:

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

-pe_-l4_mBY
anubhava
  • 761,203
  • 64
  • 569
  • 643
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
  • 497,756
  • 71
  • 530
  • 681
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
  • 175,061
  • 34
  • 275
  • 318
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,413
  • 2
  • 7
  • 17
-1

also with rev/cut/rev

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

pqrstuvwxyz

man rev => rev - reverse lines characterwise

hoijui
  • 3,615
  • 2
  • 33
  • 41
karakfa
  • 66,216
  • 7
  • 41
  • 56