简体   繁体   中英

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.

#!/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.

万一你想知道重命名:

rename 's/(.*)a(.*)/$1b$2/' *

This simple bash script could work for you, but assumes, the files are exactly 3 characters long (see the ?a? in the -name tag of find ), and a is in the middle.

#!/bin/bash


while IFS= read -r -d '' file; do

    # 'find' command returns files with a './' prefixed before the name.
    # So the target file name is extracted from starting at position 2 i.e.
    # starting of file-name for a length of 1 character. The string 'b' is
    # appended and the rest of the file-name from index 4 is suffixed after 
    # that

    mv -v "$file" "${file:2:1}b${file:4}"

done < <(find . -maxdepth 1 -mindepth 1 -type f -name "?a?" -print0)

You can see it working as below

$ touch 1a1 2a2 3a3 44a44
$ ls
1a1  2a2  3a3 44a44
$ ./script.sh
`./1a1' -> `1b1'
`./2a2' -> `2b2'
`./3a3' -> `3b3'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM