【问题标题】:ubuntu bash printing result in system with extra ""ubuntu bash 打印导致系统带有额外的“”
【发布时间】:2015-01-07 13:06:02
【问题描述】:

为什么我的 A 的结果有 "" 并且只在我的 B 正常时捕获第一个单词?

文件:sample.txt

Amos Tan:Sunny Day:22.5:3:2 
Jason Ong:Rainy Day:20.5:3:2 
Bryan Sing:Cloudy Day:29.5:3:2 

终端代码:

cat ./sample.txt | while read A B
do 
    title=`echo “$A” | cut -f 1 -d ":"`
    echo "Found $title"
    author=`echo “$B” | cut -f 2 -d ":"`
    echo "Found $author
done

结果:

Found “Amos”
Found Sunny Day
Found “Jason”
Found Rainy Day
Found “Bryan”
Found Cloudy Day

【问题讨论】:

    标签: linux bash ubuntu terminal


    【解决方案1】:

    这行是问题所在:

    cat ./sample.txt | while read A B
    

    它将第一个单词读入A,并将该行的其余部分读入变量B

    你可以更好地使用:

    while read -r line
    do 
        title=$(echo "$line" | cut -f 1 -d ":")
        echo "Found title=$title"
        author=$(echo "$line" | cut -f 2 -d ":")
        echo "Found author=$author"
    done < ./sample.txt
    

    或者干脆使用awk:

    awk -F : '{printf "title=%s, author=%s\n", $1, $2}' sample.txt
    

    【讨论】:

    • 非常感谢它有帮助。但我有另一个关于逻辑的问题。我的标题和作者是组合的主键。如果用户输入相同的标题和作者,则提示用户再次输入,否则继续其他输入。我试过了,但没有用。
    • book_title="" book_author="" book_price=0.0 echo "请输入书名:" read book_title echo "请输入书名:" read book_author while read -r line do title=$ (echo "$line" | cut -f 1 -d ":") author=$(echo "$line" | cut -f 2 -d ":") if [ "$title" = "$book_title" ] & [ "$author" = "$book_author" ] then echo "用户存在,请重新输入书名和作者" echo "请输入书名:" read book_title echo "请输入书名:" read book_author else echo "请输入书的价格:“ read book_price fi done
    • 你能否发布这个有问题的脚本,因为从 cmets 部分无法理解。
    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 2011-11-11
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多