Backreferences in sed returning wrong value

13,364

Solution 1

You must surround between parentheses the data to reference it later, and sed begins to count in 1. To recover all the characters matched without the need of parentheses, it is used the & symbol.

sed 's/-\([0-9]\)/\/\1/g' input.txt

That yields:

/www/file-name/1

Solution 2

You need to capture using parenthesis before you can back reference (which start a \1). Try sed -r 's|(.*)-|\1/|':

$ sed -r 's|(.*)-|\1/|' <<< "/www/file-name-1" 
/www/file-name/1

You can use any delimiter with sed so / isn't the best choice when the substitution contains /. The -r option is for extended regexp so the parenthesis don't need to be escaped.

Share:
13,364
user2052491
Author by

user2052491

Updated on July 29, 2022

Comments

  • user2052491
    user2052491 over 1 year

    I am trying to replace an expression using sed. The regex works in vim but not in sed. I'm replacing the last dash before the number with a slash so

    /www/file-name-1 
    

    should return

    /www/file-name/1
    

    I am using the following command but it keeps outputting /www/file-name/0 instead

    sed 's/-[0-9]/\/\0/g' input.txt
    

    What am I doing wrong?

  • user2052491
    user2052491 about 11 years
    if I use \1 it returns "\1 not defined in the RE"
  • maljub01
    maljub01 about 11 years
    This is the correct answer. I didn't notice @user2052491 was not using the parentheses.
  • Jack Wasey
    Jack Wasey over 7 years
    OS X / macOS has ancient UNIX tools. You can't use -r which means you need to escape the parentheses.
  • phil294
    phil294 almost 7 years
    the backslashes before the braces are not necessary, are they?
  • thenickdude
    thenickdude over 6 years
    OS X's sed uses -E instead of -r to enable extended regex