0

regex to look for numbers or small letter alphabets of length 46 and append 0 at the end.

C:\Users\svuppula>echo "0020000000000000100000000000000000000000000001" | sed -e 's/[0-9a-z]{45}/\10/g'
sed: -e expression #1, char 20: invalid reference \1 on `s' command's RHS

where as grep works

C:\Users\svuppula>echo "0020000000000000100000000000000000000000000001" | grep -E '[0-9a-z]{45}'
"0020000000000000100000000000000000000000000001"

versions:

C:\Users\svuppula>sed --version

sed (GNU sed) 4.2.2

C:\Users\svuppula>grep --version

grep (GNU grep) 2.24
  • 2
    Either use sed -r or escape the parentheses \{ \} and enclose the match in \([0-9a-z]\{10\}\) in case of sed -e – user218374 Mar 14 '17 at 16:23
3

\1 refers to the first group in parenthesis, but you have none. Either add the parenthesis, or use & to fill in the whole matching string:

$ echo "foobar" | sed -e 's/foo/&ABC/'
fooABCbar
$ echo "foobar" | sed -re 's/(foo)/\1ABC/'
fooABCbar

Note that you need -r in GNU sed to use the parenthesis, and also with the {NN} counting match. (unless you want to use ugly backslash escapes on all of them.)

So:

echo "0020000000000000100000000000000000000000000001" | sed -re 's/([0-9a-z]{45})/\19/g'
00200000000000001000000000000000000000000000091

That string of digits is 46 characters long, but the regex only matches 45 characters, so the nine gets added before the last digit. Anchor the regexp to the start and end of the line if you want to only process lines with exactly 45 characters.

$ echo "002000000000000010000000000000000000000000001" | sed -re 's/^[0-9a-z]{45}$/&9/g'
0020000000000000100000000000000000000000000019

(I changed the number added to a nine so that it doesn't get mixed with the zeroes in the input.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.