开发者

Format stdin in bash

开发者 https://www.devze.com 2022-12-29 05:16 出处:网络
I have a multi-line string coming from another program that I want to convert to a SQL command.I was开发者_运维知识库 hoping that printf could help me, but it doesn\'t seem to work:

I have a multi-line string coming from another program that I want to convert to a SQL command. I was开发者_运维知识库 hoping that printf could help me, but it doesn't seem to work:

echo -e '1\n2\n3'|printf 'SELECT %s INTO MyTable'

I was hoping to see:

SELECT '1
2
3' INTO MyTable

But I got:

SELECT  INTO MyTable

How can I get the %s to read stdin?


Use xargs to transform stdin to program arguments:

echo -n  -e '1\n2\n3' |xargs -0  printf 'SELECT %s INTO MyTable'


Give this a try:

printf_stdin() { local stdin; read -d '' -u 0 stdin; printf "$@" "$stdin"; }

echo -e '1\n2\n3' | printf_stdin 'SELECT %s INTO MyTable'


You can't. The printf shell command formats its arguments not standard input so what you can do is provide the output of a command as a single argument:

bash$ printf "SELECT '%s' INTO MyTable" "`echo -e '1\n2\n3'`"
SELECT '1
2
3' INTO MyTable
bash$

Edit: a solution in Awk

bash$ echo -e '1\n2\n3' | awk -v 'ORS=' '
   BEGIN { print "SELECT \"" }
   { print $0, "\n" }
   END { print "\" INTO MyTable" }'
SELECT "1
2
3
" INTO MyTable
bash$

I'll leave stripping the final newline as an exercise to the reader. If you want to do anything more complex in the printf, then you will have to come up with some more creative awk script.

0

精彩评论

暂无评论...
验证码 换一张
取 消