Reputation: 735
I've modified this script from the arch forums: https://wiki.archlinux.org/index.php/Convert_Flac_to_Mp3#With_FFmpeg
I'm trying to find specific file types in a directory structure, convert them to another music file type, and place them in a "converted" directory that maintains the same directory structure.
I'm stuck at stripping the string $b
of its file name.
$b
holds the string ./converted/alt-j/2012\ an\ awesome\ wave/01\ Intro.flac
Is there a way I can remove the file name from the string? I don't think ffmpeg can create/force parent directories of output files.
#!/bin/bash
# file convert script
find -type f -name "*.flac" -print0 | while read -d $'\0' a; do
b=${a/.\//.\/converted/}
< /dev/null ffmpeg -i "$a" "${b[@]/%flac/ogg}"
#echo "${b[@]/%flac/ogg}"
Upvotes: 1
Views: 261
Reputation: 113834
I'm stuck at stripping the string
$b
of its file name.
Let us start with b
:
$ b=./converted/alt-j/2012\ an\ awesome\ wave/01\ Intro.flac
To remove the file name, leaving the path:
$ c=${b%/*}
To verify the result:
$ echo "$c"
./converted/alt-j/2012 an awesome wave
To make sure that directory c
exists, do:
$ mkdir -p "$c"
Or, all in one step:
$ mkdir -p "${b%/*}"
We are using the shell's suffix removal feature. In the form ${parameter%word}
, the shell finds the shortest match of word
against the end of parameter
and removes it. (Note that word
is a shell glob, not a regex.) In out case, word
is /*
which matches a slash followed by any characters. Because this removes the shortest such match, this removes only the filename part from the parameter.
From man bash
:
${parameter%word}
${parameter%%word}
Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the%'' case) or the longest matching pattern (the
%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
Upvotes: 2