Shell read *sometimes* strips trailing delimiter

后端 未结 2 1755
失恋的感觉
失恋的感觉 2021-01-01 23:37

To parse colon-delimited fields I can use read with a custom IFS:

$ echo \'foo.c:41:switch (color) {\' | { IFS=: read file line tex         


        
2条回答
  •  醉话见心
    2021-01-02 00:20

    One "feature" of read is that it will strip leading and trailing whitespace separators in the variables it populates - it is explained in much more detail at the linked answer. This enables beginners to have read do what they expect when doing for example read first rest <<< ' foo bar ' (note the extra spaces).

    The take-away? It is hard to do accurate text processing using Bash and shell tools. If you want full control it's probably better to use a "stricter" language like for example Python, where split() will do what you want, but where you might have to dig much deeper into string handling to explicitly remove newline separators or handle encoding.

提交回复
热议问题