為什麼模式替換對單一變數不起作用?

為什麼模式替換對單一變數不起作用?

請參閱以下會議記錄:

$ mkdir temp
$ cd temp/
$ touch file{1..5}
$ ls
file1  file2  file3  file4  file5
$ SRC=file; TGT=ram
$ for f in file* ; do mv $f ${f/$SRC/$TGT} ; done
$ ls
ram1  ram2  ram3  ram4  ram5
$ PAT=ram/file
$ for f in ram* ; do mv $f ${f/$PAT} ; done
mv: 'ram1' and 'ram1' are the same file
mv: 'ram2' and 'ram2' are the same file
mv: 'ram3' and 'ram3' are the same file
mv: 'ram4' and 'ram4' are the same file
mv: 'ram5' and 'ram5' are the same file

SRC為什麼如果我提供和TGT作為單獨的變量,模式替換會起作用,而如果我將它們作為單個變量提供,則模式替換不起作用PAT

我的理解是,替換是從裡到外處理的,因此外部大括號內的字串 ie f/$SRC/$TGTorf/$PAT應該同等地處理為f/file/ramor f/ram/file,然後再次處理以給出實際的新檔案名稱。但顯然這並沒有這樣做......

我在 Kubuntu Bionic LTS 上使用 Bash 4.4.18 並進行了最新更新。

答案1

Bash 手冊:

${parameter/pattern/string}
pattern擴展以產生一個模式,就像檔案名稱擴展一樣。 [...] 如果string為 null,則pattern刪除 的符合項,並且/可以省略下列模式。

所以,這個過程並不是在擴展之後確定模式和替換。相反,首先識別模式和替換組件,然後然後它們被擴展了。在 中${f/$PAT}, 的整體$PAT成為模式,並且替換為空。

相關內容