在 bash 中格式化标准输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2762382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:02:57  来源:igfitidea点击:

Format stdin in bash

bash

提问by User1

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:

我有一个来自另一个程序的多行字符串,我想将其转换为 SQL 命令。我希望 printf 可以帮助我,但它似乎不起作用:

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?

我怎样才能让 %s 读取标准输入?

回答by Jürgen H?tzel

Use xargsto transform stdinto program arguments:

使用xargsstdin转换为程序参数:

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

回答by Paused until further notice.

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'

回答by D.Shawley

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

你不能。在printfshell命令格式化它的参数不是标准输入,所以你可以做的是提供了一个命令,一个参数的输出:

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

Edit: a solution in Awk

编辑:Awk 中的解决方案

bash$ echo -e '1\n2\n3' | awk -v 'ORS=' '
   BEGIN { print "SELECT \"" }
   { print ##代码##, "\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.

我将剥离最后的换行符作为练习留给读者。如果您想在printf.