【问题标题】:how to prevent for loop from using space as deliminator, bash script如何防止for循环使用空格作为分隔符,bash脚本
【发布时间】:2013-08-05 16:30:09
【问题描述】:

我正在尝试纠正一个 bash 脚本,以对我公司使用的 CMS 进行多项检查和搜索。我试图为用户实现一个函数,以便能够搜索某个宏调用,并且该函数返回包含该调用的所有文件、调用宏的行以及宏调用中的实际代码。我所拥有的似乎被我使用 for 循环格式化输出的事实搞砸了。这是我正在处理的脚本的 sn-p:

    elif [ "$choice" = "2" ]
then
    echo -e "\n What macro call are we looking for $name?"
    read macrocall
    for i in $(grep -inR "$macrocall" $sitepath/templates/macros/); do 
    file=$(echo $i | cut -d\: -f1 | awk -F\/ '{ print $NF }')
    line=$(echo $i | cut -d\: -f2)
    calltext=$(echo $i | cut -d\: -f3-)
    echo -e "\nFile: $file"
    echo -e "\nLine: $line"
    echo -e "\nMacro Call from file: $calltext"
    done
fi

当前脚本运行前几个字段,直到它得到一个空格,然后一切都变得混乱。任何人都知道如何让 for 循环分隔符成为 grep 的每个结果?任何的意见都将会有帮助。如果你们中的任何人需要更多信息,请告诉我。谢谢!

【问题讨论】:

    标签: bash for-loop awk grep cut


    【解决方案1】:

    这样做的正确方法更像是:

    printf "\n What macro call are we looking for %s?" "$name"
    read macrocall
    
    # ensure globbing is off and set IFS to a newline after saving original values
    oSET="$-"; set -f; oIFS="$IFS"; IFS=$'\n'
    
    awk -v macrocall="$macrocall" '
        BEGIN    { lc_macrocall = "\\<" tolower(macrocall) "\\>" }
        tolower($0) ~ lc_macrocall {
            file=FILENAME
            sub(/.*\//,"",file)
            printf "\n%s\n", file
            printf "\n%d\n", FNR
            printf "\nMacro Call from file: %s\n", $0
        }
    ' $(find "$sitepath/templates/macros" -type f -print)
    
    # restore original IFS and globbing values
    IFS="$oIFS"; set +f -"$oSET"
    

    这解决了最初请求的文件名中包含空格的问题,但也处理了文件名中的通配符,以及各种典型的echo 问题。

    【讨论】:

      【解决方案2】:

      您可以将内部字段分隔符$IFS(通常设置为空格、制表符和换行符)设置为仅换行符来解决此问题:

      IFS="\n"
      

      【讨论】:

      • 这很容易。谢谢!
      猜你喜欢
      • 2012-04-19
      • 2020-06-17
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      相关资源
      最近更新 更多