In linux shell bash script, how to print to a file on the same line?

In linux shell bash script, how to print to a file on the same line?

At each iteration

I used

echo "$variable1" >> file_name, echo "$variable2" >> file_name, 

but echo inserts a new line so that it becomes

  $v1 $v2 

not

  $v1 \tab $v2 

"\ c" cannot eat a newline character.

this post is a BASH shell script echo to output on the same line

Does not help.

thanks

+4
source share
4 answers

After going through this question, I decided you were looking for echo -n .

+6
source

If you are looking for one tab between variables, then printf is a good choice.

 printf '%s\t%s' "$v1" "$v2" >> file_name 

If you want it to be exactly like your example, where the tab is padded with space on both sides:

 printf '%s \t %s' "$v1" "$v2" >> file_name 
+3
source

Several variants:

  • echo -n foo bar This is simple, but may not work on some older UNIX systems, such as HP-UX or SunOS. Instead, -n will be printed, along with the rest of the arguments, followed by a new line.
  • echo -e "foo bar\c" . The value \c makes sense: "do not produce any additional 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 is quite portable as well as flexible.
+2
source

Use echo -n to trim a newline. See if it works

+1
source

Source: https://habr.com/ru/post/1389965/


All Articles