使用不同分隔符时 Bash cut 命令中的空格字符问题

发布于 2024-11-14 10:26:19 字数 428 浏览 3 评论 0原文

我已经设置|作为 cut 命令的分隔符,但空格字符似乎仍然被解释为分隔符。

这是我的测试脚本:

people[1]="Mr|Smith"
people[2]="Mrs|Jane Brown"

for person in ${people[@]}
do
    title=$(echo $person | cut -f1 -d\|)
    name=$(echo $person | cut -f2 -d\|)
    echo $title $name
    echo
done

哪些输出:

Mr Smith

Mrs Jane

Brown Brown

任何人都可以解释为什么 Jane Brown 中的空格字符会导致问题吗?

谢谢 西蒙

I have set | to be the delimiter for a cut command, but space characters seem to still be interpreted as a delimiter too.

Here's my test script:

people[1]="Mr|Smith"
people[2]="Mrs|Jane Brown"

for person in ${people[@]}
do
    title=$(echo $person | cut -f1 -d\|)
    name=$(echo $person | cut -f2 -d\|)
    echo $title $name
    echo
done

Which outputs:

Mr Smith

Mrs Jane

Brown Brown

Can anyone shed some light on why the space character in Jane Brown is causing problems?

Thanks
Simon

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月牙弯弯 2024-11-21 10:26:19

${people[@]} 用双引号引起来:

for person in "${people[@]}"
...

否则,Mrs|Jane Brown 将被解释为 2 个单独的标记:Mrs|Jane棕色

将其视为:

for i in "a b c"; do echo $i; done # echoes "a b c" just once

for i in a b c; do echo $i; done # does an echo for a, b and c

Enclose ${people[@]} in double quotes:

for person in "${people[@]}"
...

Otherwise, Mrs|Jane Brown will get interpreted as 2 separate tokens: Mrs|Jane and Brown.

Think of it as:

for i in "a b c"; do echo $i; done # echoes "a b c" just once

versus

for i in a b c; do echo $i; done # does an echo for a, b and c
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文