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 ?

1
  • 1
    Try sed -e 's/[^A-Za-z0-9._-]/_/g' -e 's/$/.sif/' <<< $tor
    – fpmurphy
    Commented Nov 16, 2020 at 4:48

1 Answer 1

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.

3
  • Or simpler: sed -e 's/[^[:alnum:].-]/_/g' <<< "$tor".sif
    – Freddy
    Commented Nov 16, 2020 at 13:21
  • why always quote variable expansions?
    – moth
    Commented Nov 17, 2020 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
    Commented Nov 17, 2020 at 17:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .