Reading file line by line (with space) in Unix Shell scripting - Issue

后端 未结 2 1733
时光取名叫无心
时光取名叫无心 2020-12-08 15:59

I want to read a file line by line in Unix shell scripting. Line can contain leading and trailing spaces and i want to read those spaces also in the line. I tried with \"whi

2条回答
  •  甜味超标
    2020-12-08 16:16

    You want to read raw lines to avoid problems with backslashes in the input (use -r):

    while read -r line; do
       printf "<%s>\n" "$line"
    done < file.txt
    

    This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

    while IFS= read -r line; do
       printf "%s\n" "$line"
    done < file.txt
    

    This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

    Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

提交回复
热议问题