0

I have a path like this:

dirname=../2Reconnaissance-annoted/J39/IMG_2208.json

I want to get a new path by replacing ".json" with "_json", so I tried this command:

tr "\.json" "_json" <<<$dirname

The problem is that I get:

__/2Reconnaissance-annoted/J39/IMG_2208_json

Rather than

../2Reconnaissance-annoted/J39/IMG_2208_json

How do you fix it, please?

Momog
  • 567
  • 7
  • 27
  • 1
    try this: ```dirname=${dirname/.json/_json}``` – Xosrov Jun 03 '19 at 09:34
  • Possible duplicate of [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/q/4651437/608639), [How to assign the output of a Bash command to a variable?](https://stackoverflow.com/q/2314750/608639), etc. – jww Jun 03 '19 at 11:09

1 Answers1

1

tr does transliteration, i.e. it replaces a character by a character, not a string by a string. What you need is substitution.

Most shells support substitution directly:

dirname=${dirname/.json/_json}

(${dirname/%.json/_json} would only substitute the substrings at the end of the string).

If your shell doesn't support it, you can use sed:

echo "$dirname" | sed -e 's/\.json$/_json/'
choroba
  • 231,213
  • 25
  • 204
  • 289