简体   繁体   English

如何替换bash中的文件夹和文件名?

[英]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'. 我的输入是目录的路径,例如“ / Images”。 In folder 'Images', I have folders such as 'Mary', 'Kate' etc. Those folders, contain images such as 'Kate #1.png' 'Kate #2.png'. 在文件夹“图像”中,我有诸如“玛丽”,“凯特”等文件夹。这些文件夹包含诸如“凯特#1.png”,“凯特#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'. 我想将“图像”中的所有文件夹名称更改为“玛丽”,“凯特”等。并将所有文件名称更改为“ 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. 如果打印的mv ..命令正确,请在命令末尾添加|sh ,它将为您完成工作。

Inside your directory Images/, an option could be 在目录Images /中,可以选择

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 for type in df; do ...; done for type in df; do ...; done since the type is the only thing that changes; for type in df; do ...; done ,因为类型是唯一改变的事情; 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. 如果您不喜欢文件名未更改时的警告,则可以先检查f和新文件是否相同。

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 正如您所说的,输入是目录,我假设您将其作为命令行参数$ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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