0

I am using below code

    #! /bin/bash
for host in $(cat ./server.txt)
do 
    echo "$host"

done

server.txt contains :

     server1.com
     server2.com

     server3.com


     server4.com

But the above code is giving below output:

     server1.com
     server2.com
     server3.com
     server4.com

i.e its not taking account of empty lines.How can I fix that?

Monojit
  • 195
  • 2
  • 3
  • 14

3 Answers3

5
while read host; do echo "$host"; done < server.txt

With the code you provided, the file as a single string is given as the 4th argument to the for command. The shell then splits the string using arbitrary whitespace as a delimiter (assuming you have not altered the IFS variable).

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

empty lines are not there because they are considered whitespaces used to separate word values.

use this:

awk '{print $1}' server.txt

 server1.com
 server2.com

 server3.com


 server4.com
johnshen64
  • 3,734
  • 1
  • 21
  • 17
  • you mean "whitespace used to separate *words*" – glenn jackman Mar 29 '12 at 19:29
  • Printing is not the main concern here, I need to store values in variable. – Monojit Mar 29 '12 at 19:29
  • glenn. thanks, you are right. i meant to say values, not vars. i have now edited it. grails, thanks for pointing out the difference. i did not realize that you want the variable in the shell environment only. – johnshen64 Mar 29 '12 at 20:00
0

Alternative

s=$(cat -E ./server.txt) 
while [ ${#s} != 0 ]
 do
  echo ${s%%\$*}
  s=${s#*\$}
 done
pizza
  • 7,296
  • 1
  • 25
  • 22