Bash – Replace underscores with spaces for all files in directory

bashrename

For all files in a directory, I want to replace the underscores in the filename with spaces.

I tried this solution, which does the opposite of what I want: https://stackoverflow.com/questions/1806868/linux-replacing-spaces-in-the-file-names

But switched the space with the underscore. That does not work, giving the error

´x´ is not a directory

Where x is the last word in the filename, for example hello_world_x

What is the correct command to replace underscores with spaces for all files in a directory?

Best Answer

After you cd to the correct directory, this script will reliably solve your need (not portable because of the ${var//pat/str} expansion):

#!/bin/bash

set -- *_*
for file; do
    mv -- "$file" "${file//_/ }"
done

*_* The glob *_* will select all files that have an _ in their names.

set -- Those names (even including spaces or new-lines) will be reliably set to the positional parameters $1, $2, etc. with the simple command set -- "list"

for file; Then, each positional parameter will be (in turn) assigned to the var file.

do ... done contains the commands to execute (for each $file).

mv -- "$file" "${file//_/ }" will move (rename) each file to the same name with each (all) _ replaced by (space).

Note: You may add the -i (interactive) option to avoid overwriting already existing files. If the file exist, mv will ask. With a caveat: there needs to be an interactive shell where mv could communicate with the user.

mv -i -- "$file" "${file//_/ }"