How to use `while read` (Bash) to read the last line in a file if there’s no newline at the end of the file?

后端 未结 7 884
臣服心动
臣服心动 2020-12-02 13:58

Let’s say I have the following Bash script:

while read SCRIPT_SOURCE_LINE; do
  echo \"$SCRIPT_SOURCE_LINE\"
done

I noticed that for files

7条回答
  •  甜味超标
    2020-12-02 14:45

    @Netcoder's answer is good, this optimisation eliminates spurious blank lines, also allows for the last line not to have a newline, if that's how the original was.

    DONE=false
    NL=
    until $DONE ;do
    if ! read ; then DONE=true ; NL='-n ';fi
    echo $NL$REPLY
    done
    

    I used a variant of this to create 2 functions to allow piping of text that includes a '[' to keep grep happy. (you can add other translations)

    function grepfix(){
        local x="$@";
        if [[ "$x" == '-' ]]; then
          local DONE=false
          local xx=
          until $DONE ;do
             if ! IFS= read ; then DONE=true ; xx="-n "; fi
             echo ${xx}${REPLY//\[/\\\[}
          done
        else
          echo "${x//\[/\\\[}"
        fi
     }
    
    
     function grepunfix(){
        local x="$@";
        if [[ "$x" == '-' ]]; then
          local DONE=false
          local xx=
          until $DONE ;do
             if ! IFS= read ; then DONE=true ; xx="-n "; fi
             echo ${xx}${REPLY//\\\[/\[}
          done
        else
          echo "${x//\\\[/\[}"
        fi
     }
    

    (passing - as $1 enables pipe otherwise just translates arguments)

提交回复
热议问题