[英]How to extract specific parts of the path and filename in linux
我當前的任務是將多個目錄中的許多文件重命名為不同的標識符。
所以我有幾個目錄,例如:b01,b02,b03等。每個目錄中都有文件名,例如img01.23495.png,img01.3596596.png,img02.2399495.png等。
我必須將b01的img01重命名為其他標識符。 因此,標識符取決於目錄名稱和文件名的第一部分。
我對管道的想法是:獲取所有png文件名,提取其所在的文件夾,提取img ##部分,然后將信息存儲到文件中,因此我將得到一個類似以下內容的文件:
b01 img01
b01 img02
b02 img01
...
這很有用,因此我可以在后記中指定新標識符作為第三列,然后讀入文件以執行實際的重命名。
目前,我有./images/something/b01/img01.2342394.png之類的路徑。
為了獲得列表,我目前正在嘗試類似find . | grep png | something sed | sort | uniq > indentifiers.txt
find . | grep png | something sed | sort | uniq > indentifiers.txt
但是,我被困在sed
部分。 同樣,歡迎提出任何建議來做我想做的事情。
find . -name "*.png" | sed 's#^.*/\([^/]*\)/\([^/.]*\)\.[0-9]\+\.png$#\1 \2#' | sort -u
對不起,我不能得到完整的測試-我在工作和停留在OSX,里面有奇怪的sed
問題。 無論如何,解決方案的核心(使用-name
測試進行find
和-u
標志進行sort
)是sed正則表達式。 您似乎有能力,但是如果有人發現它,我將解釋整個過程:
s - Search and Replace
# - Delimiter (Search pattern)
^ - Beginning of a line
. - Any character
* - zero or more times
/ - a literal '/'
\( - start a capturing group
[^/]* - Any character except '/', zero or more times
\) - End capturing group (#1)
/ - a literal '/'
\( - start a capturing group
[^/.]* - Any character except '/' or '.', zero or more times
\) - End capturing group (#2)
\. - a literal '.'
[0-9] - a digit
\+ - one or more times
\.png - a literal '.png'
$ - end of the line
# - Delimiter, now starting the replace pattern
\1 - the contents of the first capturing group
- a space
\2 - the contents of the second capturing group
# - Delimiter. End of all patterns.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.