像 {} 這樣的 replstr 是什麼?

像 {} 這樣的 replstr 是什麼?

在文件中xargs提到了該-I標誌所採用的「replstr」。當我發現要執行以下命令時,我開始閱讀有關它的內容fswatch

fswatch -0 -e ".*" -i ".rb" . | xargs -0 -n 1 -I {} ruby {}

並開始閱讀手冊頁xargs

-I replstr
        Execute utility for each input line, replacing one or more occurrences of replstr in up to replacements (or 5 if no -R flag is
        specified) arguments to utility with the entire line of input.  The resulting arguments, after replacement is done, will not be
        allowed to grow beyond 255 bytes; this is implemented by concatenating as much of the argument containing replstr as possible, to
        the constructed arguments to utility, up to 255 bytes.  The 255 byte limit does not apply to arguments to utility which do not
        contain replstr, and furthermore, no replacement will be done on utility itself.  Implies -x. 

想想術語“replstr”似乎可能意味著“讀取評估列印循環字串”,這是它的縮寫嗎?我開始擺弄它,試著了解{}正在做什麼,但我不確定我是否真的明白了:

➜  scripts git:(master) ✗  {0..3}
zsh: command not found: 0..3
➜  scripts git:(master) ✗ echo {0..3}
0 1 2 3
➜  scripts git:(master) ✗ echo {a..3}
a ` _ ^ ] \ [ Z Y X W V U T S R Q P O N M L K J I H G F E D C B A @ ? > = < ; : 9 8 7 6 5 4 3
➜  scripts git:(master) ✗ echo {a..d}
a b c d
➜  scripts git:(master) ✗ echo cats and dogs | xargs
cats and dogs
➜  scripts git:(master) ✗ echo cats and dogs | xargs {}
xargs: {}: No such file or directory
➜  scripts git:(master) ✗ echo cats and dogs | xargs {} echo {}
xargs: {}: No such file or directory
➜  scripts git:(master) ✗ echo cats and dogs | xargs -I {}

➜  scripts git:(master) ✗ echo cats and dogs | xargs -I {} echo {}
cats and dogs

例如,echo {a..3}對我來說確實沒有意義。它看起來確實像是在做一些“在這裡替換這個字串列表”的事情,但我不確定這是否是正確的看待它的方式。另外,我不確定{}replstr 是否是特定類型,以及是否有更多類型,或者 replstr 是否只是一對大括號之間的任何內容。希望獲得有關 replstr 以及如何處理它們的一些指導。

答案1

replstr意思是“替換字串”或“替換字串”。

原來的 replstr 是{}.它首先是用find命令exec子句引入的,其中它被找到的每個檔案名稱替換,例如

find /tmp -name "foo*" -exec echo file {} found \;

將顯示,假設兩個檔案符合該模式:

file foo1 found
file foo2 found 

xargs命令允許對從傳遞到其標準輸入的字串建立的參數執行相同的操作,並且還允許指定與{}替換字串不同的內容。

請注意,預設的 replstr 只是{}大括號內沒有任何內容,後者用於不同的目的,例如您已經注意到的範圍或參數擴展。

答案2

-I參數的工作方式如下:-I whatever意味著字面上出現的whatever被命令參數替換。演示:

$ echo "a
b
c" | xargs -I f echo hey f hey f
hey a hey a
hey b hey b
hey c hey c

看?xargs取出每一行ab、 和c,並將它們替換為fin echo hey f hey f

沒有{}涉及。

-I選項是 POSIX。 GNUxargs記錄了一個已棄用的-i選項,如果呼叫該選項,其-iwhatever行為類似於-I whatever.如果直接呼叫-i它的行為就像-I {}.在這種情況下,出現的{}被替換。{}顯然受到以下特徵的啟發find:其-exec謂詞。

{a..b}而Bash語法則foo{a,b,c}bar透過其「大括號擴展」來處理。{}沒有特殊意義,按原樣傳遞給命令。 (如果不是,它將破壞符合標準的、常見的find呼叫。)

答案3

{...}shell 的大括號展開,它支援列表{a,b,c}(擴展為a,bc),以及數字序列{0..13}(擴展為數字0, 1... 12, 13)或字元{a..d}a, b, c, d)。 (大括號擴展與{}所使用的佔位符無關xargs)。

擴展為有點奇怪的序列{a..3}可以通過以下方式解釋ASCII 字元表。由於a不是數字,兩者都被視為字符,並且擴展為字符代碼數值中a和之間的所有字符。3碰巧a出現在 後面3,因此該序列是向下遍歷大寫字母和數字 9 到 3。

如所見,在這樣的範圍內混合字母和數字並不是很有用,但{a..z}{A..Z}可能有用,以及在正則表達式和 shell 全局中類似的[a-z]and 。 [A-Z](也就是說,如果您可以忽略其餘字母。)

相關內容