如何在shell脚本中提取文件的一部分

时间:2015-07-31 12:04:27

标签: regex bash shell

我有一个日志文件,我必须解析它们。 我想提取这个日志文件的一部分意味着 两个正则表达式之间的任何东西都可以捕获。 像

reg="(COPY\s+role\s+\(id\,\s+name\,\s+access\_level.*)"

regex="END"

这两个正则表达式之间的所有行都应该能够捕获。 为此,我试过

echo "Enter the file to extract"
read file

reg="(COPY\s+role\s+\(id\,\s+name\,\s+access\_level.*)"
regex="END"

if [[ $file =~ $reg ]];then
 while read LINE

 echo ${BASH_REMATCH[1]}
if[[ $LINE =~ $regex ]];then
break;
fi
 done < $file

但我无法捕捉任何东西。请建议做什么 如果我让它变得更复杂,而不是建议我如何做到这一点。

3 个答案:

答案 0 :(得分:0)

你需要使用之前的查找和查找之后:

在查找之前

是?&lt; = 查找后是?=

如果您之前使用正则表达式替换下面的“before_pattern”,之后使用正则表达式替换“after_pattern”,则应该捕获之间的所有内容。

pattern = before_pattern everything in between after_pattern
regex = (?<=before_pattern)(.*)(?=after_pattern)
result = " everything in between "

我希望这会有所帮助。

答案 1 :(得分:0)

我认为你的if应该在你的内心,如果你想检查每一行。

state=outside
while read line; do
  if [[ $state = outside ]] && [[ $line =~ $begin_regex ]]; then
    state=inside
  fi
  if [[ $state = inside ]]; then
    printf "%s\n" "$line"
    if [[ $line =~ $end_regex ]]; then
      state=outside
      # or break if you only want to do this once
    fi
  fi
done < "$file"

答案 2 :(得分:0)

Check this out:

 seq 100 | sed -n '/70/,/80/p'

This print everything between the first matched line and the second matched line inclusive (more than once if multiple matched segments exist). 70 and 80 are actually regular expressions, for example, you could write

eq 100 | sed -rn '/^7./,/^8/p'