why empty line is not getting stored in variable

2020-05-08 06:23发布

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?

标签: bash shell
3条回答
Summer. ? 凉城
2楼-- · 2020-05-08 06:47
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).

查看更多
干净又极端
3楼-- · 2020-05-08 06:49

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
查看更多
4楼-- · 2020-05-08 06:51

Alternative

s=$(cat -E ./server.txt) 
while [ ${#s} != 0 ]
 do
  echo ${s%%\$*}
  s=${s#*\$}
 done
查看更多
登录 后发表回答