在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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:58:48  来源:igfitidea点击:

In Linux shell bash script, how to print to a file at the same line?

linuxbashshell

提问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

这篇 BASH shell 脚本回显到同一行输出

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 -nto 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:

那里有几个选项:

  1. echo -n foo barIt'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.
  2. echo -e "foo bar\c". The \chas meaning: "produce no further output". I don't like this solution personally, but some UNIX wizards use it.
  3. printf %b "foo bar"I like this solution the most. It's quite portable as well flexible.
  1. echo -n foo bar这很简单,但可能不适用于某些旧的 UNIX 系统,如 HP-UX 或 SunOS。相反,将打印“-n”以及其他参数,然后是新行。
  2. echo -e "foo bar\c". 其\c含义为:“不再产生进一步的输出”。我个人不喜欢这个解决方案,但一些 UNIX 向导使用它。
  3. printf %b "foo bar"我最喜欢这个解决方案。它非常便携,也很灵活。