0

In order to write files to a USB volume I want to rename filenames containing '?', '"', '*' or ':' to replace any of these characters with a space. But I'm having trouble with the '*'. My bash script is

for file in * 
do 
    mv -v "'"$file"'" "'"$(echo "$file" | sed 's/\(.*\)[?"*:]\(.*\)/\1 \2/')"'" 
done

The '*' keeps getting expanded into the filenames in the current directory. I've tried using

set -f

but then the initial 'in *' doesn't work.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
ottotts
  • 13
  • Related: https://stackoverflow.com/questions/102049/how-do-i-escape-the-wildcard-asterisk-character-in-bash – Panki Nov 15 '18 at 12:27
  • @Panki Thanks, but I thought I'd done that. Exactly how should it be written? – ottotts Nov 15 '18 at 12:36

2 Answers2

3

Just make sure that you quote you filenames properly and there will be no issues.

for name in ./*; do
    newname=${name//[?\"*:]/ }
    if [ "$newname" != "$name" ]; then
        mv -iv "$name" "$newname"
    fi
done

Your "'"$file"'" actually leaves $file completely unquoted (surrounded by single quotes, but these do not quote the variable or its value since they are themselves quoted).

See also:


Regarding your sed bit.

sed has a neat little command that many seem to overlook called y:

sed 'y/?"*:/    /'

This would change all characters in the first part of the expression to the corresponding character in the second part (here all spaces).

tr works too:

tr '?"*:' '    '

But in this case, it would be more convenient to use the built in parameter substitution facility of bash to make the changes needed.

Kusalananda
  • 333,661
0

You have some strange stuff happening with you quotes.

Start by changing the "'" to "