分割文件打破
比方说,你有以下输入文件分割文件打破
Some text. It may contain line
breaks.
Some other part of the text
Yet an other part of
the text
你想要遍历每个文本部分(由两个换行符(\n\n
)分隔),所以在第一次迭代是 我只会得到:
Some text. It may contain line
breaks.
在第二次迭代我会得到:
Some other part of the text
而在最后一次迭代我会得到:
Yet an other part of
the text
我尝试这样做,但它似乎并没有工作,因为IFS
只支持一个角色?
cat $inputfile | while IFS=$'\n\n' read part; do
# do something with $part
done
这是anubhava纯bash的解决方案:
#!/bin/bash
COUNT=1; echo -n "$COUNT: "
while read LINE
do
[ "$LINE" ] && echo "$LINE" || { ((++COUNT)); echo -n "$COUNT: " ;}
done
用AWK与空RS
:
awk '{print NR ":", $0}' RS= file
1: Some Text. It may contains line
breaks.
2: Some Other Part of the Text
3: Yet an other Part of
the Text
你可以清楚地看到你的输入文件有3条记录现在(每个记录印有记录#输出)。
我如何可以遍历与一个'while'或'for'循环,如你问题出? – MarcDefiant
使用'awk',你不需要循环迭代,因为awk通过记录处理输入记录。你可以使用每个记录(用'$ 0'表示)和文件由awk – anubhava
oops,没有看到你的答案...张贴副本... :(+1和删除我的。 – Kent
我最终使用了这个变体(没有COUNT),因为我有awk解决方案的问题。我的文本部分包含很多像'''或'''这样的字符,需要通过'system()'调用传递给另一个脚本。 – MarcDefiant