1

我有一个如下所示的文本文件:

[1] Header information Timestamp Text begins
Text continues
Text continues
Text continues

[2] Header information Timestamp Text begins
Text continues
Text continues

[3] Header information Timestamp Text begins
Text continues
Text continues
Text continues

我想读入该文件,并单独处理每个条目(它们在 1 到 20 或 30 行之间)。

有没有办法使用空行作为分隔符来循环文件?

4

2 回答 2

4

答案是肯定的!

awk -vRS="" '...'将空白行视为行拆分器。

以你的例子和测试:

kent$  cat b.txt
[1] Header information Timestamp Text begins
Text continues
Text continues
Text continues

[2] Header information Timestamp Text begins
Text continues
Text continues

[3] Header information Timestamp Text begins
Text continues
Text continues
Text continues

kent$  awk -vRS="" '{print "==== new block here ===="}1' b.txt  
==== new block here ====
[1] Header information Timestamp Text begins
Text continues
Text continues
Text continues
==== new block here ====
[2] Header information Timestamp Text begins
Text continues
Text continues
==== new block here ====
[3] Header information Timestamp Text begins
Text continues
Text continues
Text continues
于 2013-02-06T17:51:22.013 回答
0

这是一个纯粹的bash解决方案:

{
    read -r block    # First line only
    while read -r; do
        if [[ $REPLY =~ ^$ ]]; then
            # Do what you like with the contents 
            # $block here, then ...
            block=""
        else
            block+="$REPLY"
        fi
    done
 } < file.txt
于 2013-02-06T18:24:35.347 回答