2016-11-07 28 views
0

需要建立一個字符串foobar is not foo and not bar如何在bash中獲得printf格式的特定參數?

我期待類似的代碼:

$ printf "%1%2 is not %1 and not %2" 'foo' 'bar' 

那麼,如何通過一個特定的參數?

我ENV:

$ bash --version 
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu) 
+3

'printf'接受與C中'printf'相同的格式化字符串以及一些其他對shell腳本有用的選項。其中一些附加選項也是依賴於外殼的。但是,似乎在格式字符串中的多個位置重複參數不受支持或不可移植。你應該通過重複的論證兩次,每個位置一次。 –

回答

-3

的語法是C相同printf函數。

$ printf '%1$s%2$s is not %1$s and not %2$s' 'foo' 'bar' 

其實如果你只是需要連接一些字符串,你不需要printf。您可以在字符串中使用命名變量:

a=foo 
b=bar 
echo "$a$b is not $a and not $b" 
+1

'bash'內置'printf'不支持'n $'。 – chepner

+0

非詳盡的調查:它與'zsh'和'ksh'的內置'printf'以及外部BSD'printf'一起使用。它在'bash',POSIX'sh'或者'GNU'coreutils'的一部分'printf'中不起作用。 – chepner

+0

@chepner你使用哪個版本的'bash'?我的4.3.46甚至沒有'printf'內建。 – ea7ababe

相關問題