6

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

At each iteration,

I used

 echo "$variable1"  >> file_name, 

 echo "$variable2"  >> file_name, 

but echo insert a newline so that it becomes

 $v1

 $v2 

not

     $v1 \tab  $v2

"\c" cannot eat newline.

this post BASH shell script echo to output on same line

does not help .

thanks

Community
  • 1
  • 1
user1002288
  • 4,860
  • 10
  • 50
  • 78

4 Answers4

7

After wading through that question, I've decided that what you're looking for is echo -n.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

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

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
jordanm
  • 33,009
  • 7
  • 61
  • 76
2

few options there:

  1. 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.
  2. 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.
  3. printf %b "foo bar" I like this solution the most. It's quite portable as well flexible.
Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85
1

Use echo -n to trim the newline. See if that works

schwert
  • 61
  • 6