2011-09-22 31 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 
相关问题