Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backreferences in sed returning wrong value

Tags:

regex

macos

sed

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?

like image 282
user2052491 Avatar asked Mar 03 '13 17:03

user2052491


2 Answers

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
like image 117
Birei Avatar answered Nov 12 '22 10:11

Birei


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.

like image 5
Chris Seymour Avatar answered Nov 12 '22 12:11

Chris Seymour