Search code examples
linuxshellmv

linux shell command mv many files


I have many files like 1a1, 2a2, 3a3 and I want to mv the file names to 1b1, 2b2, 3b3. That means to replace 'a' to 'b' in these file names.

I have tried the command like:

for f in */*; do
  mv "$f" "${f/a/b}"
done
ls | xargs -i mv {} ${{}/a/b}  
ls | xargs -i mv {} \`echo {}|tr -t 'a' 'b'\`

but none works. I know a command rename 'a' 'b' * can work.

But I still want to figure out how to use for, xargs involved with other cmds to do this work. After all, in every day use, they are much general than simple rename command.

Please help me, thanks.


Solution

  • #!/bin/bash
    for old in *
    do new=$(echo "$old" | sed -e 's/a/b/')
       echo mv "$old" "$new" &>2
       mv "$old" "$new"
    done
    

    This example will allow you to guess more complex name transformations as you learn how to use sed(1) command to do the name transformations.

    The program walks all the command line parameters to the for loop, in each loop, the program gets a new variable new with the transformation of the original $old name. Then you only have to execute the command with the old and new values.