leetbacoon
leetbacoon

Reputation: 1249

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

Upvotes: 3

Views: 2226

Answers (5)

karakfa
karakfa

Reputation: 67507

also with rev/cut/rev

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

pqrstuvwxyz

man rev => rev - reverse lines characterwise

Upvotes: -1

ctac_
ctac_

Reputation: 2491

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

Upvotes: 2

tripleee
tripleee

Reputation: 189679

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

Upvotes: 2

chepner
chepner

Reputation: 531868

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

Upvotes: 3

anubhava
anubhava

Reputation: 785611

You can use this sed with a capture group:

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

-pe_-l4_mBY

Upvotes: 6

Related Questions