在第n个特殊字符出现之间提取文件

时间:2015-07-16 06:19:27

标签: shell awk sed

我需要在两个第n次出现的特殊字符之间提取文件中的文本。 Linux“财富”数据由“”字符分隔。我有一个脚本可以计算次数,然后在范围内选择一个rnd数。现在我需要在的n-1和n次出现之间提取文件

#!/bin/bash
# get a fortune message 
MESSAGES=$(tr -cd % < fortune.dat | wc -c) # number of messages
MSG=$(shuf -i 1-$MESSAGES -n 1)            # rnd message in range
echo $MSG                                  # got what I expected
awk 'NR==n' RS=% n=$MSG fortune.dat        # <-- solution

示例 fortune.dat 文件:

"Three people can keep a secret,
if two of them are dead!"
Ben Franklin
%
Anger is like acid, they both
destroy the container that holds them.
Chinese proverb
%
Storms make oaks take roots.
Proverb
%
If you do not hope, you will not find what is beyond your hopes.
St. Clement of Alexandra
%

1 个答案:

答案 0 :(得分:5)

在%(n-1)和第n次出现%之间获取文本的最简单方法是:

awk 'NR==n' RS=% n=$MSG input-file