0

part of my code is as below :

output=$(cat databaselog | awk '{print $9,$1,$2,$6}' )
echo $output >> savedfile

Output will be something like this , saved in a new file called savedfile

name1 date1 id1 ip1 name2 date2 id2 ip2 name3 date3 id3 ip3

But i want it to be like this:

name1 date1 id1 ip1
name2 date2 id2 ip2
name3 date3 id3 ip3

i know its quite easy , but i cant find the right way to do it , pls help thanks!

1 Answers1

2

You need to double-quote $output as "$output" when you echo it. Otherwise the output will have newlines and other white-space transformed into just spaces.

It's also good practice to double-quote the command substitution. output="$(...)" instead of just output=$(...)

e.g.

output="$( cat databaselog | awk '{print $9,$1,$2,$6}' )"
echo >> savedfile
echo "$output" >> savedfile

But you'd be better off with just:

echo >> savedfile
awk '{print $9,$1,$2,$6}' databaselog >> savedfile
cas
  • 78,579
  • Interesting. I also thought that quoting the command substitution was necessary, but recently someone pointed out to me that this was not necessary in an immediate variable assignment (so quoting only the $output should be sufficient). Do you have an authoritative source on that? – AdminBee May 28 '21 at 07:14
  • Nope, no source. Just habit and a vague recollection that it matters in some cases, and like anything involving shell quoting: "double-quote unless you know for sure that you want word-splitting to happen". Also, one of the many advantages of $() over backticks is that not only can you nest the command substitutions, you can also nest the quoting in the different sub-shell levels. Double-quoting "$output" when using it (e.g. with the echo) is the crucial thing to avoid newlines etc being transformed into spaces. – cas May 28 '21 at 07:18
  • one more question @cas , what if i want to have a spacing from the previous entry everytime when i do this >> savedfile, – Wenhan Xiao May 28 '21 at 07:22
  • @WenhanXiao do you mean an extra blank line? just echo or printf it. i'll edit my answer to show. – cas May 28 '21 at 07:25
  • @cas big thanks mate ! sorry i am still new to all this – Wenhan Xiao May 28 '21 at 07:28
  • @cas hey buddy, any idea how to display .html files in console instead of firefox ? – Wenhan Xiao May 28 '21 at 09:12
  • use a text mode browser like lynx or links. Or just cat or less if you want to see the raw html. BTW, I know you're just trying to be friendly so I'm not offended, but I don't like being called buddy or mate or pal etc. In Australia, words like that are aggressive fighting words unless they come from someone who's a good, known friend. – cas May 28 '21 at 12:36