在Linux shell bash脚本中,如何打印到同一行的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8782346/
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
In Linux shell bash script, how to print to a file at the same line?
提问by user1002288
In Linux shell bash script, how to print to a file at the same line ?
在 Linux shell bash 脚本中,如何打印到同一行的文件?
At each iteration,
在每次迭代中,
I used
我用了
echo "$variable1" >> file_name,
echo "$variable2" >> file_name,
but echo insert a newline so that it becomes
但 echo 插入一个换行符,使其变为
$v1
$v2
not
不是
$v1 \tab $v2
"\c" cannot eat newline.
"\c" 不能吃换行符。
this post BASH shell script echo to output on same line
does not help .
没有帮助。
thanks
谢谢
回答by Ignacio Vazquez-Abrams
After wading through that question, I've decided that what you're looking for is echo -n
.
在仔细研究了这个问题之后,我决定你要找的是echo -n
.
回答by schwert
Use echo -n
to trim the newline. See if that works
使用echo -n
修剪的换行符。看看这是否有效
回答by jordanm
If you are looking for a single tab in between the variables, then printf is a good choice.
如果您正在寻找变量之间的单个选项卡,那么 printf 是一个不错的选择。
printf '%s\t%s' "$v1" "$v2" >> file_name
If you want it exactly like your example where the tab is padded with a space on both sides:
如果您希望它与您的示例完全一样,其中选项卡在两侧都填充有空格:
printf '%s \t %s' "$v1" "$v2" >> file_name
回答by Micha? ?rajer
few options there:
那里有几个选项:
echo -n foo bar
It's simple, but may not work on some old UNIX systems like HP-UX or SunOS. Instead the "-n" will be printed as well as the rest of the arguments followed by new line.echo -e "foo bar\c"
. The\c
has meaning: "produce no further output". I don't like this solution personally, but some UNIX wizards use it.printf %b "foo bar"
I like this solution the most. It's quite portable as well flexible.
echo -n foo bar
这很简单,但可能不适用于某些旧的 UNIX 系统,如 HP-UX 或 SunOS。相反,将打印“-n”以及其他参数,然后是新行。echo -e "foo bar\c"
. 其\c
含义为:“不再产生进一步的输出”。我个人不喜欢这个解决方案,但一些 UNIX 向导使用它。printf %b "foo bar"
我最喜欢这个解决方案。它非常便携,也很灵活。