agf1997
agf1997

Reputation: 2898

Modify a path stored in a bash script variable

I have a variable f in a bash script

f=/path/to/a/file.jpg

I'm using the variable as an input argument to a program that requires and input and an output path.

For example the program's usage would look like this

./myprogram -i inputFilePath -o outputFilePath

using my variable, I'm trying to maintain the same basename, change the extension, and put the output file into a sub directory. For example

./myprogram -i /path/to/a/file.jpg -o /path/to/a/new/file.tiff

I'm trying to do that by doing this

./myprogram -i "$f" -o "${f%.jpg}.tiff"

of course this keeps the basename, changes the extension, but doesn't put the file into the new subdirectory.

How can I modify f to to change /path/to/a/file.jpg into /path/to/a/new/file.tiff?

Upvotes: 0

Views: 1549

Answers (3)

drldcsta
drldcsta

Reputation: 423

If you're on a system that supports the basename and dirnamecommands you could use a simple wrapper function eg:

$ type newSubDir
newSubDir is a function
newSubDir ()
{
    oldPath=$(dirname "${1}");
    fileName=$(basename "${1}");
    newPath="${oldPath}/${2}/${fileName}";
    echo "${newPath}"
}

$ newSubDir /path/to/a/file.jpg new
/path/to/a/new/file.jpg

If your system doesn't have those, you can accomplish the same thing using string manipulation:

$ file="/path/to/a/file.jpg"

$ echo "${file%/*}"
/path/to/a

$ echo "${file##*/}"
file.jpg

Upvotes: 1

ErikMD
ErikMD

Reputation: 14763

Actually you can do this in several ways:

  1. Using sed as pointed out by @anubhava
  2. Using dirname and basename:

    ./myprogram -i "$f" -o "$(dirname -- "$f")/new/$(basename -- "$f" .jpg).tiff"
    
  3. Using only Bash:

    ./myprogram -i "$f" -o "${f%/*}/new/$(b=${f##*/}; echo -n ${b%.jpg}.tiff)"
    

Note that unlike the second solution (using dirname/basename) that is more robust, the third solution (in pure Bash) won't work if "$f" does not contain any slash:

$ dirname "file.jpg"
.
$ f="file.jpg"; echo "${f%/*}"
file.jpg

Upvotes: 2

anubhava
anubhava

Reputation: 786291

You may use this sed:

s='/path/to/a/file.jpg'
sed -E 's~(.*/)([^.]+)\.jpg$~\1new/\2.tiff~' <<< "$s"

/path/to/a/new/file.tiff

Upvotes: 1

Related Questions