1

I have a directory with some tif files I want to merge together depending on file suffixes (note the spaces in the file names):

File1 P1.tif
File1 P2.tif
File1 P3.tif
File2 P1.tif
File2 P2.tif

should result in merged tifs:

File1.tif
File2.tif

I have

for i in *\ P1.tif; do
    match=${i/\ P1/\ P*}
    out=${i/\ P1/}
    echo "processing $match"
    tiffcp "$match" "$out"
done

$match will contain File1 P*.tif and $out will contain File1.tif. but tiffcp will handle the first argument as a string and won't find a matching file. if a do not use quotes around $match the spaces in the file names will result in no matching file

so the question is: how do I pass a globbing string as an argument to a command?

2

If you want globbing to be performed upon parameter expansion (which by the way is performed by the shell, prior to calling the command; the command sees the resulting files, not the pattern), that's where you'd leave the parameter expansion unquoted.

Leaving a parameter expansion unquoted implies both word splitting and globbing (sometimes referred to as a conceptual split+glob operator). Here, you only want the globbing part, so you'd need to disable the splitting part (by assigning an empty value to the special $IFS variable):

IFS= # disable splitting
for i in ./*\ P1.tif; do
    match=${i/\ P1/\ P*}
    out=${i/\ P1/}
    echo "processing $match"
    tiffcp $match "$out" # split+glob on $match
done

That assumes the leading part of the file name doesn't contain wildcard characters. Alternatively, you could do:

for i in ./*\ P1.tif; do
    prefix=${i%\ P1.tif}
    out=$prefix.tif
    echo "processing $prefix"
    tiffcp "$prefix P"*.tif "$out"
done

That way, only that * is taken as a glob operator, and that code also has the advantage of only using standard sh syntax.

Note that glob expansions are sorted lexically, so P10 would come before P2. Use zsh and its numericglobsort option (or n glob qualifier) for numeric sorting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.