1

How can I replace all the occurrences of the + character in all the filenames in the current working directory with the space character?

I know that there's the linux command rename but I'm not sure how I'd use it to do this.

Example:

Early+Christians -> Early Christians

1

3 Answers 3

3

Try:

rename -n 'y/+/ /' *

y is used for translating characters from one set to another. Consider the example from man rename:

To translate uppercase names to lower, you'd use
       rename 'y/A-Z/a-z/' *

The -n is used for testing out the expression. Once you're satisfied with the results, run rename without it to perform the actual renaming.

I should mention that the rename I am talking of is perl-rename, known as prename (and available as rename) on Debian-based Linux distros, the same command seen in ntzrmtthihu777's answer.

2
  • @AvinashRaj for simple translations it's better to use y (or tr) over s: perlmonks.org/?node_id=327021
    – muru
    Commented Dec 2, 2014 at 6:01
  • @AvinashRaj yes. That's what y does. Try it: perl -pe 'y/a/b/' <<<'aaaaaaaaaaa'
    – muru
    Commented Dec 2, 2014 at 6:06
2

You could also use mv to rename files. Copy and paste this into terminal or turn it into a script:

for f in *; do
    # check if its a file
    if [[ -f "$f" ]]; then
        new_name=$(echo "$f" | sed 's/+/ /g')
        # replace this echo with mv
        echo "$f" "$new_name"
    fi
done

Replace the second echo with mv if you are satisfied with the results. As it will rename all the files in the directory that loop is run in.

2
  • I think you're escaping the wrong character there (\ instead of \+).
    – muru
    Commented Dec 2, 2014 at 4:24
  • @muru thanks for bringing that up. I just ran it again and it seems that escaping the characters isn't necessary. It runs the same in single and double quotes, escaped or not.
    – jmunsch
    Commented Dec 2, 2014 at 4:30
0

Personally I love using perl-rename for such tasks. For instance, I'd use perl-rename 's:_: :g' file_name_here to change all underscores to spaces, resulting in file name here. You can think of it as a sed rename thing :)

Not the answer you're looking for? Browse other questions tagged .