让我们假设我有一个具有以下格式的大文件:
======start=========
id:xxxxxxxxx
.............
.............
======end===========
======start=========
id:xxxxxxxxx
............
............
======end===========
如何根据输入的ID提取那些文本块?
答案 0 :(得分:2)
尝试使用以下类似方法grep
:
$ grep id -A2 file.txt
根据您的示例,它将仅返回==start==
和==end==
之间的文本
id:xxxxxxxxx
.............
.............
--
id:xxxxxxxxx
............
............
答案 1 :(得分:1)
由于我主要是PHP用户,所以这是PHP版本:
另存为bigparser.php
<?php
if(empty($argv[2])){
die('run as '.$argv[0].' bigfile.txt my-section-id');
}
$filename = $argv[1];
$section = $argv[2];
$handle = fopen($filename, "r") or die("Couldn't get file");
$printBuffer = false;
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
if($printBuffer===true){
if(trim($buffer)=="======end==========="){
die();
}
echo $buffer;
} elseif(trim($buffer)=='id:'.$section){
$printBuffer=true;
continue;
}
}
fclose($handle);
}
并运行为:
php bigparser.php myfilename.txt abcdefg
其中abcdefg
当然是id:abcdefg
希望有帮助。