Reading input files by line using read command in shell scripting skips last line

前端 未结 5 551
日久生厌
日久生厌 2020-12-01 09:51

I usually use the read command to read an input file to the shell script line by line. An example code such as the one below yields a wrong result if a new line isn\'t inser

5条回答
  •  执念已碎
    2020-12-01 10:14

    Use while loop like this:

    while IFS= read -r line || [ -n "$line" ]; do
      echo "$line"
    done 

    Or using grep with while loop:

    while IFS= read -r line; do
      echo "$line"
    done < <(grep "" file)
    

    Using grep . instead of grep "" will skip the empty lines.

    Note:

    1. Using IFS= keeps any line indentation intact.

    2. You should almost always use the -r option with read.

    3. Don't read lines with for

    4. File without a newline at the end isn't a standard unix text file.

提交回复
热议问题