I am trying to do some simple formatting stuff with ‘sed’ in linux, and i need to use a regex to trim a string after the 15th character, and append a ‘…’ to the end. Something like this:
before: this is a long string that needs to be shortened after: this is a long ...
Can anyone please show me how i could write this as a regex, and if possible explain how it works so that i might learn regex a little better?
The following works for me:
What happens here is that we match any character (
.) 15 times ({15}). We capture the text so matched inside parentheses. The following part (.+$) matches all the rest, until the end of the line. We replace this by whatever we’ve captured inside the parentheses (\1), followed by the hyperbolic ellipsis.To satisfy
sed‘s regex dialect (BRE) we have to escape some of the characters.