以块为单位而不是逐行读取文件?

时间:2013-02-06 17:47:15

标签: bash

我有一个看起来像这样的文本文件:

[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行)。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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