Z殼

Z殼

我想為標準輸入的每一行呼叫一個命令,很像xargs,但該行應該作為標準輸入傳遞,而不是作為命令列參數傳遞:

cat some-file.txt | <magic> | wc -c
  • 這應該會列印文件每行中的字元數。

我有什麼選擇?

答案1

一個簡單的循環怎麼樣

while IFS= read -r line ;
do
   printf "%s" "$line" | wc -c
done < some-file.txt

答案2

while-read 迴圈是最清晰的。如果你想使用 xargs 為每一行做一些事情,你可能會得到像這樣的怪物:

printf "%s\n" "foo bar" one " 1 2 3" | 
xargs -d '\n' -n 1 -I LINE bash -c 'wc -c <<< "LINE"'
8
4
7

相當昂貴,因為你必須為每一行產生一個 bash 進程。

答案3

cat file.txt | while IFS= read -r i; do echo -n "$i" | wc -c; done
##  or (better):
while IFS= read -r i; do echo -n "$i" | wc -c; done < file.txt

然而,這將只是列印一行上的字元數,一次一行。如果您想要更具可讀性的內容,您可能需要以下幾個:

##  Prints the contents of each line underneath the character count:
while IFS= read -r i; do echo -n "$i" | wc -c; echo "$i"; done < file.txt
##  Prints the line number alongside the character count:
n=0; while IFS= read -r i; do n=$((n+1)); echo -n "line number $n : "; echo -n "$i" | wc -c; done < file.txt

為了獲得更大的便攜性,您可以使用printf '%s' "$i"而不是所有echo -n

答案4

Z殼

使用選項可以避免將行儲存到變數中-e

setopt pipefail
cat some-file.txt |
  
  while read -re | wc -c
  do
  done

-r\按原樣讀取s

-e回顯輸入而不是將其分配給任何變量

pipefail一旦這樣做,就會read -re | wc -c以非零狀態代碼退出read -re,它將出現在文件末尾

不幸的是,這個選項在 Bash 中不可用

相關內容