creativeDev
creativeDev

Reputation: 1123

sed regex substitution with backreference why not working?

I am trying to get the complete filenames with extension (abc.jpg) using sed.

input.txt:

sfdb/asdjfj/abc.jpg
asdfj/asdfj/abd.gif
sfdb/asdjfj/abc.jpg
sfdb/asdjfj/abc-2.jpg
asdfjk/asdjf/asdf_?/sfdb/asdjfj/abc_12.jpg
asdfj/asdfj/abdasdfj

current command:

grep ".jpg" input.txt|sed 's:/\([^/]+\.jpg\):\1:gi'

the grep is just an example for getting the specified lines (although not necessary here). I already tested my regex to get only the last '/' + filename + .jpg: https://www.regex101.com/r/5GTgak/2

Expected Output:

abc.jpg
abc.jpg
abc-2.jpg
abc_12.jpg

But I am still getting the same input file. What am I doing wrong?

Upvotes: 2

Views: 3559

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use the following command:

sed -rn 's/^.*\/([^/]+\.jpg)$/\1/gp' input.txt 

-r option allows extended regular expressions

/g - apply the replacement to all matches to the regexp, not just the first.

/p - if the substitution was made, then print the new pattern space.

Upvotes: 3

Related Questions