case 4.1
Info for unit 1 starts now
info1
info2
info3
info5 - the one I want
info6
info7
Info for unit 2 starts now
info1
info2
info3
info5 - the one I want
info6
info7
endcase 4.1这两个单元的信息在文件中打印了1000多次。
我的算法如下:
while read line
do
if line contains unit1
then current_unit=1
if line contains unit2
then current_unit2
if line contains info5
then
if current_unit = 1
then unit1_val = *the relevant info from this line*
elif current_unit = 2
then unit2_val = *the relevant info from this line*
if both unit1_val > 20 && unit2_val > 20
then pass简而言之:提取我需要的值,如果在某个点上两个值都超过了某个值,则测试通过。我也尝试使用Bash来实现这一点
为了清晰而编辑:我的问题是传入和传出if语句的变量。我的解析和比较很好,但是当我到达最后的if时,值不在那里,因为它们是来自if - fi的本地值(或者不是来自,视情况而定)。
编辑2:
if [[ $line == *"info5"* ]]
then
CURRENT_UNIT=5
fi
if [[ $line = *"info6"* ]]
then
CURRENT_UNIT=6
fi
if [[ $line =~ "text i want" ]]
then
if [[ $CURRENT_UNIT -eq 5 ]]
then
UNIT_5_MEM=$(awk '/Used heap/ { gsub(/M/, " "); print $4 }')
elif [[ $CURRENT_VC -eq 6 ]]
then UNIT_6_MEM=$(awk '/Used heap/ { gsub(/M/, " "); print $4 }')
fi
fi
if [[ $UNIT_5_MEM -gt 20 && $UNIT_6_MEM -gt 20 ]]
then
echo "Passed"
fi发布于 2012-10-05 19:20:39
我猜想您发布这个问题的原因是,一旦while循环结束,在while循环中设置的变量似乎就消失了。
这是因为当您将while循环作为管道的一部分执行时,它在一个子shell中运行,并且当子shell退出时,父shell的环境保持不变,不受该子shell中发生的任何事情的影响。
在bash中,您可以通过使用重定向或流程替换而不是管道来获取输入数据,从而解决此问题。例如,这不起作用:
cat inputfile | while read line; do
case "$line" in
foo*) output=$line ;;
esac
done
echo "output=$output"然而这确实是可行的:
while read line; do
case "$line" in
foo*) output=$line ;;
esac
done < inputfile
echo "output=$output"这是我想出来的:
#!/bin/bash
declare -A output
while read line; do
case "$line" in
*unit*)
unit=$(awk '{print $4}' <<<"$line")
;;
info5*)
output[$unit]="$line"
echo "FOUND: unit=$unit, line=$line" >&2
;;
esac
done < inp1
echo "Output 1:"
printf "%s\n" "${output[@]}"
### Alternately:
echo "Output 2:"
for ((i=${#output[@]}; i > 0; i--)); do
echo "unit=$i, line=${output[$i]}"
done我得到的输出是:
FOUND: unit=1, line=info5 - the one I want
FOUND: unit=2, line=info5 - the one I want
Output 1:
info5 - the one I want
info5 - the one I want
Output 2:
unit=2, line=info5 - the one I want
unit=1, line=info5 - the one I want如果你真的想把东西存储到像UNIT_5_MEM这样的变量中,我想你可以,但是数组看起来更整洁。此外,如果看不到您正在处理的数据,就很难知道您试图使用awk实现什么,所以我的答案中没有提到这一点。
发布于 2012-10-05 18:45:29
如果您正在寻找一种简单的方法来进行这样的文本过滤,最好看看sed或[awk][1]。后者能够很容易地解析,并存储一些状态。
可能是这样的(目前未测试)
#!/bin/awk
BEGIN {
current_unit=0;
}
function check_values()
{
if(values[1]>20 && values[2]>20) {
print "PASS"
exit
}
}
/Info for unit \d starts now/ {
current_unit=$4;
}
/info5/ {
values[current_unit]=value;
check_values();
}https://stackoverflow.com/questions/12744353
复制相似问题