我的文件夾和文件結構像重命名文件外殼
Folder/1/fileNameOne.ext
Folder/2/fileNameTwo.ext
Folder/3/fileNameThree.ext
...
我如何重命名文件,使得輸出變爲
Folder/1_fileNameOne.ext
Folder/2_fileNameTwo.ext
Folder/3_fileNameThree.ext
...
這又如何在Linux shell中實現嗎?
我的文件夾和文件結構像重命名文件外殼
Folder/1/fileNameOne.ext
Folder/2/fileNameTwo.ext
Folder/3/fileNameThree.ext
...
我如何重命名文件,使得輸出變爲
Folder/1_fileNameOne.ext
Folder/2_fileNameTwo.ext
Folder/3_fileNameThree.ext
...
這又如何在Linux shell中實現嗎?
從AskUbuntu這個解決方案爲我工作。
這裏是一個bash腳本,它是:
注:此腳本不工作,如果任何文件名中包含空格。
#! /bin/bash # Only go through the directories in the current directory. for dir in $(find ./ -type d) do # Remove the first two characters. # Initially, $dir = "./directory_name". # After this step, $dir = "directory_name". dir="${dir:2}" # Skip if $dir is empty. Only happens when $dir = "./" initially. if [ ! $dir ] then continue fi # Go through all the files in the directory. for file in $(ls -d $dir/*) do # Replace/with _ # For example, if $file = "dir/filename", then $new_file = "dir_filename" # where $dir = dir new_file="${file/\//_}" # Move the file. mv $file $new_file done # Remove the directory. rm -rf $dir done
chmod +x file_name
Folder/
。./file_name
運行腳本。如果名稱是始終不變的,這可能工作,即「文件」:
for i in {1..3};
do
mv $i/file ${i}_file
done
如果你有一個數字範圍更迪爾斯,爲{x..y}
改變{1..3}
。
我用${i}_file
而不是$i_file
,因爲它會考慮$i_file
名i_file
的變量,而我們只想i
作爲附加給它的變量,file
和文字。
姓名不同:-( – TheKojuEffect 2013-04-11 15:18:36
更新你的問題! – fedorqui 2013-04-11 15:19:06
你想要做多少種不同的方式?
如果名稱不包含空格或換行符或其他有問題的字符,並且中間目錄始終爲單個數字,並且如果在文件file.list
中每個行只有一個名稱的文件列表將被重命名,許多可能的方法可以做到重命名爲:
sed 's%\(.*\)/\([0-9]\)/\(.*\)%mv \1/\2/\3 \1/\2_\3%' file.list | sh -x
你會避免通過shell中運行的命令,直到你確定它會做你想要的東西;看看生成的腳本,直到它的權利。
還有一個叫rename
的命令 - 不幸的是,有幾個實現,並不都是同樣強大的。如果你有基於Perl的(使用一個Perl的正則表達式舊名稱映射到新名稱)的一個你可以使用:
rename 's%/(\d)/%/${1}_%' $(< file.list)
我只是想問你出於好奇,如果任何'重命名'可以做到這一點(我從來沒有使用它們),因爲我確信你會知道的,你的編輯速度更快:-) – 2013-04-11 15:25:30
+1。忍不住越來越多地每天都在學習。 'rename'是我不知道的命令,對於這些情況非常強大。 – fedorqui 2013-04-11 15:32:57
我使用駱駝書第一版(Perl 4的原始編程Perl)的版本,儘管從那以後我已經稍微更新了它。請參閱源代碼中的[如何使用前綴/後綴重命名](http://stackoverflow.com/questions/208181/how-to-rename-with-prefix-suffix/208389#208389)。 – 2013-04-11 15:33:27
使用循環如下:
while IFS= read -d $'\0' -r line
do
mv "$line" "${line%/*}_${line##*/}"
done < <(find Folder -type f -print0)
該方法處理文件名和中間目錄中的空格,換行符和其他特殊字符不一定必須是單個數字。
+1:'bash'密集型,但有效。 – 2013-04-11 15:43:10
還問[askubuntu](http://askubuntu.com/q/280333/10127) – 2013-04-11 21:44:08
我已經添加了解決方案[AskUbuntu](http://stackoverflow.com/a/15953333/1433665 ) – TheKojuEffect 2013-04-12 02:32:13