如何重命名目录中带有特殊字符和空格的所有文件?

Ank*_*tha 14 linux shell-script rename

如何重命名特定目录中的所有文件,其中文件的名称中包含空格和特殊字符($ 和 @)?

我尝试使用以下rename命令将所有空格和特殊字符替换为 _:

$ ls -lrt
total 464
-rwxr-xr-x. 1 pmautoamtion pmautoamtion 471106 Jul 17 13:14 Bharti Blocked TRX Report Morning$AP@20150716.csv


$ rename -n 's/ |\$|@/_/g' *
$ ls -lrt
total 464
-rwxr-xr-x. 1 pmautoamtion pmautoamtion 471106 Jul 17 13:14 Bharti Blocked TRX Report Morning$AP@20150716.csv
$
Run Code Online (Sandbox Code Playgroud)

该命令有效,但不会对文件名进行任何更改,也不会返回任何错误。如何解决这个问题,还有其他方法吗?

fre*_*ini 11

-n标志是

--不作为

无操作:显示哪些文件将被重命名。

所以如果你没有任何变化,这是正常的。

关于你的命令,它对我有用:

$ touch "a @ test"
$ ls
a @ test
$ rename -n 's/ |\$|@/_/g' *
a @ test renamed as a___test
Run Code Online (Sandbox Code Playgroud)

也许取决于你的外壳,你必须逃避 |

$ rename -n 's/ \|\$\|@/_/g' *
Run Code Online (Sandbox Code Playgroud)

或者您可以使用[…]符号对字符进行分组:

$ rename -n 's/[ @\$]/_/g' *
Run Code Online (Sandbox Code Playgroud)


don*_*sti 9

你可以这样尝试:

for file in ./*Block*                                       
do echo mv "$file" "${file//[ ()@$]/_}"
done
Run Code Online (Sandbox Code Playgroud)

如果您对结果感到满意,请删除echobeforemv以实际重命名文件。


Ank*_*tha 1

由于该rename命令由于未知原因对我不起作用,并且我没有得到我的问题的任何其他答案,因此我自己尝试努力使重命名成为可能。这可能不是重命名文件的最佳方法,但它对我有用,这就是为什么我想将其作为答案发布,以便其他人阅读此内容可能会得到一些帮助,以按照我的方式更改文件名。

现在对我来说,我知道所有文件的名称中都会有一个特定的文本,即“块”一词。以下是重命名之前的文件名:

anks@anks:~/anks$ ls -lrt
total 4
-rw-r--r-- 1 anks anks   0 Jul 25 14:47 Bharti TRX Block Report$AP@12Jul15.csv
-rw-r--r-- 1 anks anks   0 Jul 25 14:47 Bharti TRX Block Report$HP@12Jul15.csv
-rw-r--r-- 1 anks anks   0 Jul 25 14:47 Bharti TRX Block Report$CH@12Jul15.csv
-rw-r--r-- 1 anks anks   0 Jul 25 14:47 Bharti TRX Block Report$KK@12Jul15.csv
-rw-r--r-- 1 anks anks   0 Jul 25 14:48 Bharti TRX Block Report$UW@12Jul15.csv
Run Code Online (Sandbox Code Playgroud)

现在我编写了一个小的 shell 脚本来实现这一点。以下是代码:

#!/bin/bash

PATH="/home/ebfijjk/anks"

# Put the old filenames in a file.
ls $PATH | grep Block >> oldValues

# Put the new names without " " or "@" or "$" in another file
cat oldValues | sed 's/\$/_/g' | sed 's/\@/_/g' | sed 's/ /_/g' >> newValues

# Create a new file with Old names and New names seperated by a #.
paste -d'#' oldValues newValues >> oldAndNew

# Read the file with both old and new names and rename them with the new names.
while IFS='#'; read oldValue newValue
do
    mv "$oldValue" "$newValue"

done < oldAndNew

rm oldValues newValues oldandNew
Run Code Online (Sandbox Code Playgroud)

就是这样,当我运行脚本时,它会重命名所有包含空格 ( ) 或$或 的文件名,而@不是_这些字符。

  • @Archemar - 或简单地 `sed 's/[ ()@$]/_/g'` 或 `sed 'y/ ()@$/_____/'` (2认同)