开发者

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

开发者 https://www.devze.com 2023-03-11 11:06 出处:网络
I have set | to be the delimiter for a cut command, but space characters seem to still be interpreted as a delimiter too.

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 开发者_Go百科$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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消