简体   繁体   中英

How to replace folder and file names in bash?

I have the a lot of folders with spaces and capital letters, and files with spaces and hashtags. I would like to get rid of the spaces and capital letters in all sub folders in one folder, and change the file names to the ones without spaces and hashtags. How can I do that?

My input is path to directory, for example '/Images'. In folder 'Images', I have folders such as 'Mary', 'Kate' etc. Those folders, contain images such as 'Kate #1.png' 'Kate #2.png'. I would like to change all folder names in 'Images' to 'mary', 'kate' etc. And all file names to 'kate1.png', 'kate2.png'.

cd yourPath

then give this two lines a try:

find . -type d|awk -vq='"' '{o=$0;gsub(/[# ]/,"");$0=tolower($0)}$0!=o{printf "mv %s%s%s %s%s%s\n",q,o,q,q,$0,q}' 
find . -type f|awk -vq='"' '{o=$0;gsub(/[# ]/,"");$0=tolower($0)}$0!=o{printf "mv %s%s%s %s%s%s\n",q,o,q,q,$0,q}' 

If printed mv .. commands correct, add |sh to the end of the commands, it will do the job for you.

Inside your directory Images/, an option could be

find . -mindepth 1 -type d | while read f; do mv -v "$f" "$(echo "$f" | tr [:upper:] [:lower:] | tr -d ' #')"; done
find . -mindepth 1 -type f | while read f; do mv -v "$f" "$(echo "$f" | tr [:upper:] [:lower:] | tr -d ' #')"; done

Both lines could also be combined into one by surrounding them with for type in df; do ...; done for type in df; do ...; done for type in df; do ...; done since the type is the only thing that changes; but I think this is easier to understand.

If you don't like the warning when the file name does not change, you could check before if f and the new file are the same.

EDIT : Here is a small stand-alone script to accomplish your task. As you say your input is the directory, I assume you pass it to the script as command line argument $1

#!/bin/bash

if [ -z "$1" ]; then
    echo "usage: $0 directory"
    exit -1
fi

cd "$1"

for type in d f
do
    find . -mindepth 1 -type $type | while read f
    do 
        mv -v "$f" "$(echo "$f" | tr [:upper:] [:lower:] | tr -d ' #')"
    done
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