繁体   English   中英

"如何在 Bash 的循环中正确存储变量?"

[英]How to properly store variable in a Loop in Bash?

请问如何在一段时间内循环? 他是我尝试创建一个以特定方式生成数据的文件。 我的目标是将规则附加到一行中,而不管申请号是多少。

我的代码是:

#!/bin/bash
file="temp3"
while IFS= read -r line
do
        # display $line or do somthing with $line
                #printf '%s\n' "$line"
                echo
                printf '%s\n' "$line" | grep "MySource" | awk '{printf " " $5}'
                printf '%s\n' "$line" | grep "MySource-" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyDestination" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyAppName" | awk '{printf " " $8}' #| awk '{printf " " $7 " " $8}'

                VARIABLE=$(printf '%s\n' "$line" | grep "source" | awk '{printf " " $5}')
                VARIABLE=$(printf '%s\n' "$line" | grep "source-" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "destination" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "application" | awk '{printf " " $8}')

                done <"$file"

echo $VARIABLE
printf $VARIABLE

此代码可以帮助您做得更好

#!/bin/bash
while IFS=" " read -ra line; do
    # Set last Element equal to last element in array line avoid use awk
    lastElement=${line[-1]:-"Default value here"}

    echo "${line[4]} $lastElement ${line[-2]} where is the rest of the data ???"
# # For use a var here
# done <<<"$myVar"
done <log.txt

输出是。

new-rule-162 MySourceName source-address where is the rest of the data ???
new-rule-162 MyDestinationName destination-address where is the rest of the data ???
new-rule-162 MyApplicationName application where is the rest of the data ???

注意:您不需要为了 grep 打印,只需执行: grep -q "Some string" <<<"$line"

if (grep -q "Some string" <<<"$line"); then
   Do some stuff     
fi

或者

(grep -q "Some text" <<<"$lone") && echo "Found" || echo "Not found"

我假设像new-rule-162<\/code>这样的标签是独一无二的。

$ cat input-file

zone lab zone trust  new-rule-162 match source-address MySourceName
zone lab zone trust  new-rule-162 match destination-address MyDestinationName
zone lab zone trust  new-rule-162 match application MyApplicationName
zone lab zone trust  new-rule-162 then permit


$ awk '
    $(NF-1)=="source-address"{src[$5]=$NF}      # Record src; index by 5th field (new-rule-162)
    $(NF-1)=="destination-address"{dst[$5]=$NF} # and dest
    $(NF-1)=="application"{app[$5]=$NF}         # and app name
    END {
        for (i in src)                          # For all entries
            printf "%s source-address %s destination-address %s application %s\n", i, src[i], dst[i], app[i]; # print the required parameters
        }' input-file

new-rule-162 source-address MySourceName destination-address MyDestinationName application MyApplicationName

暂无
暂无

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

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