我想指望通过这个循环如何将grep输出存储到循环内的变量中?
cd /System/Library/Extensions
find *.kext -prune -type d | while read d; do
codesign -v "$d" 2>&1 | grep "invalid signature"
done
我如何可以存储或计算的输出产生的输出是多少?如果尝试与数组,计数器等,但似乎我无法得到任何东西之外的任何循环。
我想指望通过这个循环如何将grep输出存储到循环内的变量中?
cd /System/Library/Extensions
find *.kext -prune -type d | while read d; do
codesign -v "$d" 2>&1 | grep "invalid signature"
done
我如何可以存储或计算的输出产生的输出是多少?如果尝试与数组,计数器等,但似乎我无法得到任何东西之外的任何循环。
为了获得由while循环产生的行数时,wc
字计数可用于
cd /System/Library/Extensions
find *.kext -prune -type d | while read d; do
codesign -v "$d" 2>&1 | grep "invalid signature"
done | wc -l
wc -l
-l选项计数在输入线的数量,这是通过管道输送到的while
现在,如果你需要计算grep
输出的数量在while循环的每次迭代中的-c
选项的输出grep
将是有用的。
cd /System/Library/Extensions
find *.kext -prune -type d | while read d; do
codesign -v "$d" 2>&1 | grep -c "invalid signature"
done
-c
禁止正常输出;而是为每个输入文件打印一条匹配行 非常感谢! wc -l命令完成了任务。我最终改变了两件事:1)在“wc -l”之后添加了“| tr -d''”,以删除出现在输出中的一对不需要的空格。 2)我通过包装代码将结果存储在变量中,如下所示:output = $(code) – DavidD 2014-11-09 08:52:19
@DavidD欢迎您随时:)很高兴知道我有些帮助 – nu11p01n73R 2014-11-09 10:17:24
subshell中的经典难点是将变量传递回来。
这里一个方式来获得这些信息反馈:
cd /System/Library/Extensions
RESULT=$(find *.kext -prune -type d | {
# we are in a sub-subshell ...
GCOUNT=0
DIRCOUNT=0
FAILDIR=0
while read d; do
COUNT=$(codesign -v "$d" 2>&1 | grep -c "invalid signature")
if [[ -n $COUNT ]]
then
if [[ $COUNT > 0 ]]
then
echo "[ERROR] $COUNT invalid signature found in $d" >&2
GCOUNT=$(($GCOUNT + $COUNT))
FAILDIR=$(($FAILDIR + 1))
fi
else
echo "[ERROR] wrong invalid signature count for $d" >&2
fi
DIRCOUNT=$(($DIRCOUNT + 1))
done
# this is the actual result, that's why all other output of this subshell are redirected
echo "$DIRCOUNT $FAILDIR $GCOUNT"
})
# parse result integers separated by a space.
if [[ $RESULT =~ ([0-9]+)\ ([0-9]+)\ ([0-9]+) ]]
then
DIRCOUNT=${BASH_REMATCH[1]}
FAILDIR=${BASH_REMATCH[2]}
COUNT=${BASH_REMATCH[3]}
else
echo "[ERROR] Invalid result format. Please check your script $0" >&2
fi
if [[ -n $COUNT ]]
then
echo "$COUNT errors found in $FAILDIR/$DIRCOUNT directories"
fi
您需要的数量为每'协同设计-v“$ d” 2>&1'或整体while循环的次数? – nu11p01n73R 2014-11-08 10:59:35