使用較小的匹配標頭從大文件中檢索文本

使用較小的匹配標頭從大文件中檢索文本

如果第一個標題與原始檔案相符以查找要​​搜尋的標題,我需要提取兩個標題之間的文本,例如:

&Header1

1231241241313124123213123214124123213213124124123123212

1231231231231231231231231231232131242141241241231325552

2132141241232132132132141251232132142142132132132142412

&Header2

1231241241313124123213123214124123213213124124123123212

2132141241232132132132141251232132142142132132132142412

&Header3

1231241241313124123213123214124123213213124124123123212

1231231231231231231231231231232131242141241241231325552

213214124123213213213214125123213214

還有我的原始檔:

&Header1

&Header3

因此僅檢索 header1 和 3 以及以下數字資訊。

答案1

startheader=$(head -1 sourcefile)
endheader=$(tail -1 sourcefile)

# above lines assume your sourcefile has two lines in it and 
# each line contains the starting header and ending header

startlinenumber=$(grep -n "${startheader}" datafile|cut -d: -f1)
endlinenumber=$(grep -n "${endheader}" datafile|cut -d: -f1)

sed -n -e "${startlinenumber},${endlinenumber}p" datafile

我很確定,有一種更複雜的方法可以使用或awkperl單一線性sed命令來完成此操作,但我只是想明確地向您提供邏輯。您可以使用它並使其滿足您的需求。

相關內容