Extract lines between 2 tokens in a text file using bash

后端 未结 7 753
死守一世寂寞
死守一世寂寞 2020-12-05 07:26

i have a text file which looks like this:

random useless text 
 
para1 
para2 
para3 
 
random us         


        
7条回答
  •  感情败类
    2020-12-05 08:19

    Maybe sed and awk have more elegant solutions, but I have a "poor man's" approach with grep, cut, head, and tail.

    #!/bin/bash
    
    dataFile="/path/to/some/data.txt"
    startToken="token 1"
    stopToken="token 2"
    
    startTokenLine=$( grep -n "${startToken}" "${dataFile}" | cut -f 1 -d':' )
    stopTokenLine=$( grep -n "${stopToken}" "${dataFile}" | cut -f 1 -d':' )
    
    let stopTokenLine=stopTokenLine-1
    let tailLines=stopTokenLine-startTokenLine
    
    head -n ${stopTokenLine} ${dataFile} | tail -n ${tailLines}
    

提交回复
热议问题