我需要在两个第n次出现的特殊字符之间提取文件中的文本.Linux"财富"数据由" % "字符分隔.我有一个脚本,计算出现次数的百分比,然后选择范围内的一个数字.现在我需要在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
Run Code Online (Sandbox Code Playgroud)
示例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
%
Run Code Online (Sandbox Code Playgroud)
可能在%(n-1)和第n次出现之间获取文本的最简单方法是:
awk 'NR==n' RS=% n=$MSG input-file
Run Code Online (Sandbox Code Playgroud)