我有以下名為 countscript.sh 的 bash 腳本
1 #!/bin/bash
2 echo "Running" $0
3 tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed $1 q
但我不明白如何正確傳遞引數:(“3”應該是 sed 的引數 $1)。
$ echo " one two two three three three" | ./countscript.sh 3
Running ./countscript.sh
sed: -e expression #1, char 1: missing command
這作業正常:
$ echo "one two three four one one four" | tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed 3q
3 one
2 four
1 two
謝謝。
PS:有沒有人注意到
第 10 頁此腳本中的錯誤,https://www.cs.tufts.edu/~nr/cs257/archive/don-knuth/pearls-2.pdf?
uj5u.com熱心網友回復:
在參考的論文中,我認為您誤讀了
sed ${1}q
作為
sed ${1} q
并且sed不認為3本身是一個有效的命令。單獨的引數q被視為輸入檔案名。如果 的值$1 確實導致了一個有效的sed腳本,那么您很可能會收到缺少輸入檔案的錯誤q。
正確的 shell 編程將要求將其寫為
sed "${1}q"
或者
sed "${1} q"
反而; 將空格作為腳本的一部分,正確sed輸出輸入的第一$1行并退出。
有點奇怪,作者使用sed而不是head - "$1"輸出前幾行,因為其中一個(McIlroy)本質上發明了 Unix 管道的想法,作為一系列特殊用途的、狹隘的工具。沒有閱讀完整的論文,我不知道 Knuth 和 McIlroy 對論文的貢獻是什么;也許賓利只是喜歡sed。:)
uj5u.com熱心網友回復:
運行以下命令時:
$ echo " one two two three three three" | ./countscript.sh 3
特殊變數$1將替換為3您的第一個引數。因此,腳本運行:
tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed 3 q
注意 和 之間的3空格q。sed不知道該怎么做,因為你沒有給它任何命令(3不是命令)。
洗掉空間,你應該沒問題。
tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed "${1}q"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/467884.html
標籤:重击
