2017-10-19 132 views
0

我一直想:當用於發現-exec sed的文件重命名工作不

find dev-other -name '*.flac' -type f -exec echo $(echo {} | sed 's,^[^/]*/,,') \; 

我希望看到的路徑列表來.flac文件中dev-other,但沒有前置dev-other/,如:

4515/11057/4515-11057-0095.flac 
4515/11057/4515-11057-0083.flac 
4515/11057/4515-11057-0040.flac 
4515/11057/4515-11057-0105.flac 
4515/11057/4515-11057-0017.flac 
4515/11057/4515-11057-0001.flac 

相反,我看到

dev-other/4515/11057/4515-11057-0095.flac 
dev-other/4515/11057/4515-11057-0083.flac 
dev-other/4515/11057/4515-11057-0040.flac 
dev-other/4515/11057/4515-11057-0105.flac 
dev-other/4515/11057/4515-11057-0017.flac 

爲什麼不TH Ësed取代在這裏工作,即使它可以在自己的

$ echo $(echo dev-other/4515/11057/4515-11057-0047.flac | sed 's,^[^/]*/,,') 
4515/11057/4515-11057-0047.flac 

我第一次嘗試與擴展:

find dev-other -name '*.flac' -type f -exec a={} echo ${a#*/} \; 

,但得到的錯誤:

find: a=dev-other/700/122866/700-122866-0001.flac: No such file or directory 
find: a=dev-other/700/122866/700-122866-0030.flac: No such file or directory 
find: a=dev-other/700/122866/700-122866-0026.flac: No such file or directory 
find: a=dev-other/700/122866/700-122866-0006.flac: No such file or directory 
find: a=dev-other/700/122866/700-122866-0010.flac: No such file or directory 
+0

有趣的問題,以及爲什麼'sed'不行答案很可能是在這裏,https://stackoverflow.com/questions/4793892/recursively-rename-files-using -find-and-sed – CWLiu

回答

0

你可以當使用find和時,使用參數擴展3210選項,

find dev-other -name '*.flac' -type f -exec bash -c 'x=$1; y="${x#*/}"; echo "$y"' bash {} \; 

我使用利用bash -c單獨的外殼(使用bashsh),因爲涉及參數擴展分開字符串操作涉及。考慮將find結果的每個輸出作爲參數傳遞給發生此操作的子shell。

bash -c執行一個命令,該命令之後的下一個參數被用作$0(腳本的「名稱」的過程中列表),和隨後的參數成爲位置參數($1$2等)。這意味着,通過查找(取代{}的)通過文件名變爲腳本--的第一個參數,並通過$1引用的迷你腳本

如果你不想使用額外的bash,裏面使用_就地

find dev-other -name '*.flac' -type f -exec bash -c 'x=$1; y="${x#*/}"; echo "$y"' _ {} \; 

其中_ i是bash預定義的變量(在dash未定義例如):「在殼啓動時,設置爲用於調用所述殼或外殼腳本的絕對路徑名被執行在環境或參數列表中傳遞「(請參閱man bash - Special Parameters節)

值得一看Using Find - Complex Actions

+1

爲什麼不只是'... -exec sh -c'echo「$ {1#* /}」'sh {} \;'?你不需要這麼多的輔助變量... –

+0

@gniourf_gniourf:是的,但我會爭論使用一個額外的變量,我可以演示如何輸出的查找被解析在子shell內爲$ 1。儘管如此,它仍然可以避免;) – Inian