简体   繁体   中英

bash rename files issue?

I know nothing about Linux commands o bash scripts so help me please. I have a lot of file in different directories i want to rename all those files from "name" to "name.xml" using bash file is it possible to do that? I just find usefulness codes on the internet like this:

shopt -s globstar # enable ** globstar/recursivity
for i in **/*.txt; do
echo "$i" "${i/%.txt}.xml";
done

it does not even work.

For the purpose comes in handy the prename utility which is installed by default on many Linux distributions, usually it is distributed with the Perl package. You can use it like this:

find . -iname '*.txt' -exec prename 's/.txt/.xml/' {} \;

or this much faster alternative:

find . -iname '*.txt' | xargs prename 's/.txt/.xml/'

Showing */.txt */.xml means effectively there are no files matching the given pattern, as by default bash will use verbatim * if no matches are found.

To prevent this issue you'd have to additionally set shopt -s nullglob to have bash just return nothing when there is no match at all.

After verifying the echoed lines look somewhat reasonable you'll have to replace

echo "$i" "${i/%.txt}.xml"

with

mv "$i" "${i/%.txt}.xml"

to rename the files.

You can use this bash script.

#!/bin/bash
DIRECTORY=/your/base/dir/here
for i in `find $DIRECTORY -type d -exec find {} -type f  -name \*.txt\;`;
do mv $i $i.xml
done

Explanation

Move/rename all files –whatever the extension is– in current directory and below from name to name.xml . You should test using echo before running the real script.

shopt -s globstar # enable ** globstar/recursivity
for i in **; do # **/*.txt will look only for .txt files
    [[ -d "$i" ]] && continue # skip directories
    echo "$i" "$i.xml"; # replace 'echo' by 'mv' when validated
    #echo "$i" "${i/%.txt}.xml"; # replace .txt by .xml
done

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