Bash/sed: add extension to end of URL

Viewed 161

I have many files that have a line such as:

INPUTS+=('http://domain.ext/XXX/ZZZ/12345')

Which I want to modify to:

INPUTS+=('http://domain.ext/XXX/ZZZ/12345.ts') // add the ".ts" before parentheses

This is the sed command I have so far but it doesn't work as expected:

find */*.sh -type f -print0 | xargs -0 sed -i "s|\([0-9]*\)\(\x27\)|\1.ts\2|g"

How would I make this work?

Thanks!

1 Answers

You may use

sed -i "s/\([0-9]\{1,\}\)\(')\)$/\1.ts\2/g"

POSIX BRE details

  • \([0-9]\{1,\}\) - Group 1: one or more ASCII digits
  • \(')\) - Group 2: ') substring
  • $ - end of string.

The replacement is the contents of Group 1, .ts and Group 2 contents.

If you do not have to ensure there are 1+ digits before ', and can just add .ts before final ') use

sed -i "s/')$|.ts&/"

Here, ') at the end of string is matched and replaced with .ts and the match value itself (&).

See the online sed demo:

s="INPUTS+=('http://domain.ext/XXX/ZZZ/12345')"
sed "s/')$/.ts&/g" <<< "$s"
# => INPUTS+=('http://domain.ext/XXX/ZZZ/12345.ts')
sed "s/\([0-9]\{1,\}\)\(')\)$/\1.ts\2/g" <<< "$s"
# => INPUTS+=('http://domain.ext/XXX/ZZZ/12345.ts')
Related