我需要在两个第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
%
答案 0 :(得分:5)
在%(n-1)和第n次出现%之间获取文本的最简单方法是:
awk 'NR==n' RS=% n=$MSG input-file