简体   繁体   English

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

[英]Problems with space character in Bash cut command when using a different delimiter

I have set |我已设置 | to be the delimiter for a cut command, but space characters seem to still be interpreted as a delimiter too.成为cut命令的分隔符,但空格字符似乎仍被解释为分隔符。

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谢谢西蒙

Enclose ${people[@]} in double quotes:用双引号将${people[@]}括起来:

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

Otherwise, Mrs|Jane Brown will get interpreted as 2 separate tokens: Mrs|Jane and Brown .否则, Mrs|Jane Brown将被解释为 2 个单独的标记: Mrs|JaneBrown

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM