2

Hi I would like to use sed for the following task:

I have a shell variable called tor=hello:there/you/are/here and I am putting an underscore everywhere I need it to transform this shell variable in a file name with underscores like so:

sed -e 's/[^A-Za-z0-9._-]/_/g' <<< $tor

The result is this one:

hello_there_you_are_here

But I would like to add an extension like this:

hello_there_you_are_here.sif

How can I add an extension with sed at the end of the line ?

thanasisp
  • 8,122
moth
  • 307

1 Answers1

3

As user fpmurphy pointed out in comments, all you need is to add "a line of code" to Sed that says "match the end-of-line and put a .sif there". Since the "line of code" is added with -e, you get

sed -e 's/[^[:alnum:].-]/_/g' -e 's/$/.sif/' <<< "$tor"

Notice I have made some modifications. Always quote variable expansions, use "$tor" instead of $tor, as this is good practice, although not really required in the present case because Bash does not perform word splitting or globbing on here-strings. Also, [:alnum:] is a POSIX class that matches [A-Za-z0-9] in a standard locale, so it is more reliable. See, for example, Why should 'Character Classes' be preferred over 'Character Ranges'?, but take this as a small side-note.

Quasímodo
  • 18,865
  • 4
  • 36
  • 73
  • Or simpler: sed -e 's/[^[:alnum:].-]/_/g' <<< "$tor".sif – Freddy Nov 16 '20 at 13:21
  • why always quote variable expansions? – moth Nov 17 '20 at 16:28
  • 1
    @alex I have expanded on that claim. I didn't know it, but with here-strings you don't really need to quote, but in lots of cases your shell scripts can have problems if you leave variables unquoted, you don't lose anything by quoting. – Quasímodo Nov 17 '20 at 17:44