输出随机文件块除以 Bash 脚本中的任意字符

问题描述 投票:0回答:1

我有一个引号文本文件。我想每次通过 WSL 打开 bash 时输出一个引号。我知道我需要将命令放入 .bashrc 中,我的问题是知道使用哪个命令。我发现一个名为 shuf 的听起来不错,但我的引号包含换行符,而且我还没有找到允许我将引号文件除以任意字符的选项。

本质上,我需要将此 Python 代码转换为 Bash 脚本

import random

with open("csciquotes.txt", 'r') as f:
    result = random.choice(f.read().split("%"))
    print(result)

问题是找到如何模仿 .split("%")。

我已经阅读了几个问题,但没有找到任何内容,以及一些指南。

linux bash
1个回答
0
投票

您可以使用

awk
使用任意记录分隔符从文件中提取记录。您有一个看起来像这样的文件:

This is
quote 1
%
This is
quote 2
%
This is
quote 3

通过告诉

awk
%
是记录分隔符,我们可以提取特定的引号。例如:

$ for i in {1..3}; do echo === quote $i ===;  awk -vRS=% -vquotenum=$i 'NR==quotenum {print}' quotes.txt; done
=== quote 1 ===
This is
quote 1

=== quote 2 ===

This is
quote 2

=== quote 3 ===

This is
quote 3

我们唯一需要知道的是文件中包含的引号数量。我们可以通过

grep -c
得到它。要从文件中提取随机引用,我们可以结合上面的内容来执行以下操作:

# Get the total number of quotes
numquotes=$(grep -c '^%$' quotes.txt)

# Pick a random number in that range
quotenum=$(((RANDOM % numquotes) + 1))

# Extract the selected quote
awk -vRS=% -vquotenum=$quotenum 'NR==quotenum {print}' quotes.txt
© www.soinside.com 2019 - 2024. All rights reserved.