Bash, read line by line from file, with IFS

前端 未结 4 1730
独厮守ぢ
独厮守ぢ 2020-12-09 05:50

I\'m having this code from http://bash.cyberciti.biz/guide/While_loop, used to read line by line from a file

file=/etc/resolv.conf
while IFS= read -r line
         


        
4条回答
  •  执笔经年
    2020-12-09 06:22

    In the third example on that page, setting IFS to null prevents word splitting which makes that code not work. Here is that code:

    while IFS= read -r field1 field2 field3 ... fieldN
    do
        command1 on $field1
        command2 on $field1 and $field3
        ..
        ....
        commandN on $field1 ... $fieldN
    done < "/path/to dir/file name with space"
    

    As written, all the words on the line are stored in field1 and field2, etc., are empty. Change the line to this and it will work properly:

    while read -r field1 field2 field3 ... fieldN
    

提交回复
热议问题