Bash, grep between two lines with specified string

后端 未结 8 1910
栀梦
栀梦 2020-11-27 12:59

Example:

a43
test1
abc
cvb
bnm
test2
kfo

I need all lines between test1 and test2. Normal grep does not work in this case. Do you have any

相关标签:
8条回答
  • 2020-11-27 13:42

    The following script wraps up this process. More details in this similar StackOverflow post

    get_text.sh

    function show_help()
    {
      HELP=$(doMain $0 HELP)
      echo "$HELP"
      exit;
    }
    
    function doMain()
    {
      if [ "$1" == "help" ]
      then
        show_help
      fi
      if [ -z "$1" ]
      then
        show_help
      fi
      if [ -z "$2" ]
      then
        show_help
      fi
    
      FILENAME=$1
      if [ ! -f $FILENAME ]; then
          echo "File not found: $FILENAME"
          exit;
      fi
    
      if [ -z "$3" ]
      then
        START_TAG=$2_START
        END_TAG=$2_END
      else
        START_TAG=$2
        END_TAG=$3
      fi
    
      CMD="cat $FILENAME | awk '/$START_TAG/{f=1;next} /$END_TAG/{f=0} f'"
      eval $CMD
    }
    
    function help_txt()
    {
    HELP_START
      get_text.sh: extracts lines in a file between two tags
    
      usage: FILENAME {TAG_PREFIX|START_TAG} {END_TAG}
    
      examples:
        get_text.sh 1.txt AA     => extracts lines in file 1.txt between AA_START and AA_END
        get_text.sh 1.txt AA BB  => extracts lines in file 1.txt between AA and BB
    HELP_END
    }
    
    doMain $*
    
    0 讨论(0)
  • 2020-11-27 13:45

    The answer by PratPor above:

    cat test.txt | grep -A10 test1 | grep -B10 test2
    

    is cool.. but if you don't know the file length:

    cat test.txt | grep -A1000 test1 | grep -B1000 test2
    

    Not deterministic, but not too bad. Anyone have better (more deterministic)?

    0 讨论(0)
提交回复
热议问题