How can I replace all underscore chars with a whitespace in multiple file names using Bash Script? Using this code we can replace underscore with dash. But how it works with whitespace?
for i in *.mp3;
do x=$(echo $i | grep '_' | sed 's/_/\-/g');
if [ -n "$x" ];
then mv $i $x;
fi;
done;
Thank you!
This should do:
[[ "$i" = *_* ]]tests if file name contains any underscore and if it does, willmvthe file, where"${i//_/ }"expands toiwhere all the underscores have been replaced with a space (see shell parameter expansions).-ntomvmeansno clobber: will not overwrite any existent file (quite safe). Optional.-vtomvis forverbose: will say what it’s doing (if you want to see what’s happening). Very optional.--is here to tellmvthat the arguments will start right here. This is always good practice, as if a file name starts with a-,mvwill try to interpret it as an option, and your script will fail. Very good practice.Another comment: When using globs (i.e.,
for i in *.mp3), it’s always very good to either setshopt -s nullgloborshopt -s failglob. The former will make*.mp3expand to nothing if no files match the pattern (so the loop will not be executed), the latter will explicitly raise an error. Without these options, if no files matching*.mp3are present, the code inside loop will be executed withihaving the verbatim value*.mp3which can cause problems. (well, there won’t be any problems here because of the guard[[ "$i" = *_* ]], but it’s a good habit to always use either option).Hope this helps!