1

When I print a variable with one substring replacing another as described in this documentation, it behaves correctly:

stringZ='abc - 123'

echo $stringZ             # abc - 123

echo ${stringZ/ - /test}  # abctest123

However, if I get the string from a filename, the replacement is ignored completely:

for f in mp3/*; do

    stringZ=$(basename $f)

    echo $stringZ             # abc - 123.txt

    echo ${stringZ/ - /test}  # abc - 123.txt

done

How can I replace a substring in a variable derived from a filename?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

5

The answer is, as usual, that you need to always quote your variables:

$ ls -N mp3/
abc - 123.txt

Now, let's try your loop:

$ for f in mp3/*; do 
    stringZ=$(basename $f); 
    echo $stringZ; 
    echo ${stringZ/ - /test} ; 
done
basename: extra operand ‘123.txt’
Try 'basename --help' for more information.

What happens is that the $f variable has the value mp3/abc - 123.txt, so you are running basename mp3/abc - 123.txt and that complains since it sees the space and assumes that mp3/abc is the first argument. It should work as expected if you quote:

$ for f in mp3/*; do 
    stringZ=$(basename "$f"); 
    echo "$stringZ"; 
    echo "${stringZ/ - /test}" ; 
done
abc - 123.txt
abctest123.txt

Only the quotes in the basename "$f" are absolutely necessary here, but always quoting your variables is a good habit to get into.

terdon
  • 242,166