
我希望能夠做到這一點:重命名string1
並string3
添加string2
到開頭。如果找到字串 Fish 並且 Great_ = string2,則將 Fish 重新命名為 Great_Bear。
到目前為止我有這個:
ls | sed s'/\(.*\)\(string1\)\(.*\)/mv \"&\" \"\1string3\" /' | bash
這完成了目前目錄的工作。
ls -d $PWD/**/* | sed s'/\(.*\)\(string1\)\(.*\)/mv \"&\" \"\1string3\" /' | bash
這只適用於子目錄,而不適用於腳本所在的目錄。
我還想知道如何添加string2
到文件名的開頭。
答案1
我會使用rename
簡單的*/*
匹配,而不是 globstar 模式。
rename 's|([^/]+)/(.+)|$1/$1_$2|' */* -vn
我們正在配對一個目錄及其包含的內容。這比 globstar 更安全,因為我們不想遞歸太遠。
最後-n
實際上阻止了它正在做任何事物。它只會告訴你。當您確定它正確時將其刪除。不過,這裡有一個小測試工具:
$ mkdir -p test/test{1..3} && touch test/test{1..3}/file{1..3}
$ cd test
$ rename 's|([^/]+)/(.+)|$1/$1_$2|' */* -vn
test1/file1 renamed as test1/test1_file1
test1/file2 renamed as test1/test1_file2
test1/file3 renamed as test1/test1_file3
test2/file1 renamed as test2/test2_file1
test2/file2 renamed as test2/test2_file2
test2/file3 renamed as test2/test2_file3
test3/file1 renamed as test3/test3_file1
test3/file2 renamed as test3/test3_file2
test3/file3 renamed as test3/test3_file3
答案2
這應該可以解決問題:
find . -type f -exec rename -n 's/(.*)\/(.*)string1(.*)/$1\/string3$2string2$3/' {} +
find . -type f -exec
{} +
:在目前工作目錄的層次結構中遞歸搜尋文件,並執行擴展到結果清單的命令列的其餘部分;rename -n 's/(.*)\/(.*)string1(.*)/$1\/string3$2string2$3/' {} +
: 匹配任意數量的任意字元並對其進行分組,直到最後一次出現/
, 匹配 a/
, 匹配任意數量的任意字元並將其分組直至最後一次出現string1
, 匹配string1
並匹配任意數量的任意字元並將其分組;將匹配項替換為第一個捕獲組,後面跟著一個/
字符,然後string3
是第二個捕獲組,然後是string2
第三個捕獲組(-n
使rename
執行空運行;刪除它以實際重命名文件)。
% tree
.
└── dir
├── string1_bar.jpg
├── string1_foobar.jpg
└── string1_foo.jpg
1 directory, 3 files
% find . -type f -exec rename -n 's/(.*)\/(.*)string1(.*)/$1\/string3$2string2$3/' {} +
rename(./dir/string1_foo.jpg, ./dir/string3string2_foo.jpg)
rename(./dir/string1_foobar.jpg, ./dir/string3string2_foobar.jpg)
rename(./dir/string1_bar.jpg, ./dir/string3string2_bar.jpg)