gpt4 book ai didi

bash: `read` 似乎不支持 IFS

转载 作者:行者123 更新时间:2023-11-29 09:40:41 26 4
gpt4 key购买 nike

我的印象是设置 IFS 会改变 read 在将一行文本分隔成字段时使用的分隔符,但显然我遗漏了一些东西:

# OK: 'read' sees 3 items separated by spaces
$ (IFS=' '; x="aa bb cc"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'aa bb cc'
'aa' 'bb' 'cc'

# OK: 'read' sees a single item after IFS is changed
$ (IFS=','; x="aa bb cc"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'aa bb cc'
'aa bb cc' '' ''

# Why doesn't 'read' see 3 items?
$ (IFS=','; x="dd,ee,ff"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd ee ff' '' ''

# OK: 'read' sees a single item when IFS is restored.
$ (IFS=' '; x="dd,ee,ff"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd,ee,ff' '' ''

# OK: 'read' again sees 3 items separated by spaces.
$ (IFS=' '; x="gg hh ii"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'gg hh ii'
'gg' 'hh' 'ii'

为什么 IFS=',' 不让 readdd,ee,ff 解析为三个字段?

最佳答案

# Why doesn't 'read' see 3 items?
$ (IFS=','; x="dd,ee,ff"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd ee ff' '' ''

因为你没有引用你的变量。

$ ( IFS=','; x="dd,ee,ff"; echo "'$x'"; read a b c <<< "$x";\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd' 'ee' 'ff'

编辑:当未引用变量时,扩展会导致 Word Splitting :

The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting.

关于bash: `read` 似乎不支持 IFS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20948935/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com