Bash grep特定字符串并在匹配前打印一列
我需要打印匹配Protected 52周或Protected 365天后留下的一列的值。下面是我的台词Bash grep特定字符串并在匹配前打印一列,bash,grep,Bash,Grep,我需要打印匹配Protected 52周或Protected 365天后留下的一列的值。下面是我的台词 completed Protectedfor52weeks failed Protectedfor365days 对于上述行,所需输出如下所示 completed failed 具有前瞻性的grep grep -oP '\S+\s(?=Protectedfor(52weeks|365days))' file 检查所有行中的一个或两个匹配项。从注释继续,虽然您可以使用grep和扩展正则表达
completed Protectedfor52weeks failed Protectedfor365days
对于上述行,所需输出如下所示
completed failed
具有前瞻性的grep
grep -oP '\S+\s(?=Protectedfor(52weeks|365days))' file
检查所有行中的一个或两个匹配项。从注释继续,虽然您可以使用grep和扩展正则表达式匹配,或者使用sed和back引用进行匹配,但简单的方法是将其读入数组,并在迭代数组时进行测试:
#!/bin/bash
line="completed Protectedfor52weeks failed Protectedfor365days"
array=( $line )
for ((i = 0; i < ${#array[@]}; i++)); do
if [[ (${array[i]} == Protectedfor52weeks || \
${array[i]} == Protectedfor365days) && \
$i -lt $((${#array[@]} - 1)) ]]; then
echo ${array[$((i+1))]}
fi
done
awk;迭代字段并在任何所需单词之前打印字段:
awk '{for(i=1; i<=NF; ++i) if ($i ~ /^Protectedfor(52weeks|365days)$/) print $(i-1)}'
例如:
简单的答案是将该行读入一个数组,例如line=完成保护52周失败保护365天;数组=$line;对于i=0;i<${array[@]};i++;如果[${array[i]}==protectedfor52周| |${array[i]}==protectedfor365天&&i-lt${array[@]}-1]];然后echo${array[$i+1]};fi;是否总是按照相同的顺序进行,先保护52周,然后保护365天?如果您确实不需要在同一行上完成并失败,您可以使用grep-Eo[^]*protectedfor52周| 365天x2 | cut-d-f1。当特定字符串ProtectedFor 52周是行中的第一个单词时,这将跳过匹配。现在我喜欢这个解决方案,尽管它需要POSIX regex.@DavidC.Rankin您是说-P作为POSIX吗?因为-P表示使用PCRE正则表达式。。或者您突出显示了其他内容?是的,我的错误的、与Perl兼容的正则表达式:
awk '{for(i=1; i<=NF; ++i) if ($i ~ /^Protectedfor(52weeks|365days)$/) print $(i-1)}'
% awk '{for(i=1; i<=NF; ++i) if ($i ~ /^Protectedfor(52weeks|365days)$/) print $(i-1)}' <<<'completed Protectedfor52weeks failed Protectedfor365days'
completed
failed