2011-09-22 23 views
0

鑑於以下文件的內容:用printf AWK函數輸出第n個參數

 
alias command with whitespace-separated argument list 
anotheralias othercommand and its arguments 

我怎樣才能打印是這樣的:使用下面的命令

 
     alias = command with whitespace-separated argument list 
anotheralias = othercommand and its arguments 

目前我',但它是錯誤。

 
cat aliases | awk '{printf "%20s = %s\n", $1, $0}' 

回答

3
cat aliases | awk '{$1=sprintf("%20s =",$1);print}' 
+0

這省去了等號。將格式字符串變成'「%20s =」',我想。 –

+0

真實更正。 –

+0

這個工作完美,雖然'貓'是沒有必要的。然而,一個不太聰明的版本可能會更透明:'awk'{name = $ 1; $ 1 = 「」; printf「%20s =%s \ n」,名稱,$ 0}'aliases'。在'='之後沒有空格,因爲現在空的'$ 1'字段後面會出現'$ 0'的前導空格。從邏輯上講,這與上面給出的答案沒有什麼不同。它可能會幫助某人更好地理解爲什麼這個答案有效。 – dubiousjim

1
cat aliases | awk '{ printf("%20s =", $1); $1=""; printf("%s\n", $0) }' 
0

另一種方式:

sed 's/ /=/1' yourFile|awk -F= '{printf ("%20s = %s\n",$1,$2)}' 
0

只需使用shell:

while read line; do 
    set -- $line 
    cmd=$1 
    shift 
    printf "%20s = %s\n" "$cmd" "$*" 
done < filename 
相關問題