Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format stdin in bash

Tags:

bash

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?

like image 880
User1 Avatar asked May 04 '10 02:05

User1


2 Answers

Use xargs to transform stdin to program arguments:

echo -n  -e '1\n2\n3' |xargs -0  printf 'SELECT %s INTO MyTable' 
like image 139
Jürgen Hötzel Avatar answered Sep 21 '22 06:09

Jürgen Hötzel


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' 
like image 30
Dennis Williamson Avatar answered Sep 24 '22 06:09

Dennis Williamson