Getting relative paths in BASH

I have already looked for this, but I think that there was not much demand for working with paths. Therefore, I am trying to write two bash scripts to convert my music collection using tta and cue files. My directory structure is as follows: /Volumes/External/Music/Just/Some/Dirs/Album.tta for tta files and /Volumes/External/Cuesheets/Just/Some/Dirs/Album.cue for cue listing.

My current approach sets / Volumes / External as "root_dir" and gets the relative path of the album.tta file to $ ROOT_DIR / Music (in this case it will be Just / Some / Dirs / Album.tta), then add this result to $ ROOT_DIR / Cuesheets and change the suffix from .tta to .cue.

My current problem is that dirname returns the paths as they are, which means / Volumes / External / Music / Just / Some / Dirs is not converted to. / Just / Some / Dirs / when my current folder is $ ROOT_DIR / Music and the absolute path.

Add: // Here is a script if someone has similar problems:

#!/bin/bash ROOT_DIR=/Volumes/External BASE="$1" if [ ! -f "$BASE" ] then echo "Not a file" exit 1 fi if [ -n "$2" ] then OUTPUT_DIR="$HOME/tmp" else OUTPUT_DIR="$2" fi mkfdir -p "$OUTPUT_DIR" || exit 1 BASE=${BASE#"$ROOT_DIR/Music/"} BASE=${BASE%.*} TTA_FILE="$ROOT_DIR/Music/$BASE.tta" CUE_FILE="$ROOT_DIR/Cuesheets/$BASE.cue" shntool split -f "${CUE_FILE}" -o aiff -t "%n %t" -d "${OUTPUT_DIR}" "${TTA_FILE}" exit 0 
+4
source share
2 answers

If your Cuesheets directory is always in the same directory as your music, you can simply remove root_dir from the path and the remaining one the relative path. If you have a path to the .tta album in the path_ album ( album_path=/Volumes/External/Music/Just/Some/Dirs/Album.tta ) and your root_dir set ( root_dir=/Volumes/External ), just do ${album_path#$root_dir} . This truncates root_dir from the front of album_path, so you are left with album_path=Just/Some/Dirs/Album.tta .

See bash docs for more information on bash string management

EDIT: // Changed $ {$ album_path # $ root_dir} to $ {album_path # $ root_dir}

+8
source

Ok, so I solved this in several ways in the past. I do not recommend screwing paths and pwd environment variables, because of this, I saw some catastrophic events.

Here is what i will do

 CURRENTDIR=/Volumes/External/Music # make sure you check the existence in your script ... SEDVAL=$(echo $CURRENTDIR | sed s/'\/'/'\\\/'/g) #run your loops for iterating through files for a in $(find ./ -name \*ogg); do FILE=`echo $a | sed s/$SEDVAL/./g` # strip the initial directory and replace it with . convert_file $FILE # whatever action to be performed done 

If you do this often, I would just write a separate script just for that.

+1
source

Source: https://habr.com/ru/post/1382071/


All Articles