我有一个看起来像这样的文本文件:
[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行)。
有没有办法使用空行作为分隔符来循环文件?
答案 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