【问题标题】:Problems with space character in Bash cut command when using a different delimiter使用不同分隔符时 Bash cut 命令中的空格字符问题
【发布时间】:2011-06-07 15:19:51
【问题描述】:

我已设置 |成为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 中的空间角色会引起问题?

谢谢 西蒙

【问题讨论】:

    标签: bash delimiter cut shell


    【解决方案1】:

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

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

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

    把它想象成:

    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
    

    【讨论】:

      猜你喜欢
      • 2010-10-23
      • 2015-10-19
      • 2012-12-28
      • 2010-10-25
      • 2011-10-31
      • 2023-04-01
      • 2014-09-29
      • 1970-01-01
      • 2019-02-28
      相关资源
      最近更新 更多