使用 tail 時將換行符轉換為空分隔符

使用 tail 時將換行符轉換為空分隔符

如何將輸出更改為tail使用空終止行而不是換行符?

我的問題與此類似:如何在 bash 中對空分隔輸入執行「head」和「tail」?,但不同之處在於我想做類似的事情:

tail -f myFile.txt | xargs -i0 myCmd {} "arg1" "arg2"

我沒有使用find,所以不能使用-print0

這一切都是為了避免 xargs 中出現的錯誤:

xargs: unmatched double quote;
    by default quotes are special to xargs unless you use the -0 option

答案1

如果你想要最後 10 行:

tail myFile.txt | tr '\n' '\0' | xargs -r0i myCmd {} arg1 arg2

但對於 GNU xargs,您也可以將分隔符號設定為換行符:

tail myFile.txt | xargs -ri -d '\n' myCmd {} arg1 arg2

(-0-d '\0') 的縮寫。

可移植的是,您也可以簡單地轉義每個字元:

tail myFile.txt | sed 's/./\\&/g' | xargs -I{} myCmd {} arg1 arg2

或引用每一行:

tail myFile.txt | sed 's/"/"\\""/g;s/.*/"&"/' | xargs -I{} myCmd {} arg1 arg2

如果您想要最後 10 個以 NUL 分隔的記錄myFile.txt(但那樣就不是文字檔案),則必須在呼叫之前將\n其轉換為,這表示必須完全讀取該檔案:\0tail

tr '\n\0' '\0\n' < myFile.txt |
  tail |
  tr '\n\0' '\0\n' |
  xargs -r0i myCmd {} arg1 arg2

編輯(因為您在問題中更改了tailto ):tail -f

上面的最後一項顯然對 沒有意義tail -f

一個xargs -d '\n'可以工作,但對於其他的,你會遇到緩衝問題。在:

tail -f myFile.txt | tr '\n' '\0' | xargs -r0i myCmd {} arg1 arg2

tr當它不到達終端(這裡是管道)時緩衝它的輸出。 IE,它不會寫入任何內容,直到它累積了一個完整的緩衝區(大約 8kiB)要寫入的資料。這意味著myCmd將被批量調用。

tr在 GNU 或 FreeBSD 系統上,您可以使用下列命令來變更緩衝行為stdbuf

tail -f myFile.txt | stdbuf -o0 tr '\n' '\0' |
  xargs -r0i myCmd {} arg1 arg2

相關內容