read in bash on whitespace-delimited file without empty fields collapsing

前端 未结 5 1968
无人共我
无人共我 2020-11-28 14:52

I\'m trying to read a multi-line tab-separated file in bash. The format is such that empty fields are expected. Unfortunately, the shell is collapsing together field separat

5条回答
  •  情话喂你
    2020-11-28 15:00

    Here's a fast and simple function I use that avoids calling external programs or restricting the range of input characters. It works in bash only (I guess).

    If it is to allow for more variables than fields, though, it needs to be modified along Charles Duffy's answer.

    # Substitute for `read -r' that doesn't merge adjacent delimiters.
    myread() {
            local input
            IFS= read -r input || return $?
            while [[ "$#" -gt 1 ]]; do
                    IFS= read -r "$1" <<< "${input%%[$IFS]*}"
                    input="${input#*[$IFS]}"
                    shift
            done
            IFS= read -r "$1" <<< "$input"
    }
    

提交回复
热议问题