【问题标题】:bash grep 'random matching' stringbash grep '随机匹配' 字符串
【发布时间】:2011-09-16 13:57:12
【问题描述】:

有没有办法通过 bash 从文本文件中获取“随机匹配”字符串?

我目前正在通过 bash、curl 和 grep 从在线文本文件中获取下载链接。

例子:

DOWNLOADSTRING="$(curl -o - "http://example.com/folder/downloadlinks.txt" | grep "$VARIABLE")"

来自在线文本文件,其中包含

http://alphaserver.com/files/apple.zip
http://alphaserver.com/files/banana.zip

其中 $VARIABLE 是用户选择的内容。

效果很好,但我想在文本文件中添加一些镜像。

So when the variable 'banana' is selected, text file which i grep contains:

http://alphaserver.com/files/apple.zip
http://betaserver.com/files/apple.zip
http://gammaserver.com/files/apple.zip
http://deltaserver.com/files/apple.zip
http://alphaserver.com/files/banana.zip
http://betaserver.com/files/banana.zip
http://gammaserver.com/files/banana.zip
http://deltaserver.com/files/banana.zip

代码应该选择一个随机的“香蕉”字符串并将其存储为“DOWNLOADSTRING”变量。 上面的当前代码只能使用文本文件中的 1 个字符串,因为它会抓取所有“香蕉”。

这是干什么用的;我想为在线文本文件中的文件添加一些镜像下载链接,而当前代码不允许这样做。

我可以让 grep 抓取一个随机的“香蕉”字符串吗? (不是全部)

【问题讨论】:

  • 选择第一个匹配的“字符串”就足够了吗?这可以通过 grep -m 1 banana 来完成。标志 -m 指定找到的最大行数

标签: bash random grep


【解决方案1】:

查看此问题以了解如何在 grep 之后获取随机行。 rl 似乎是个不错的候选人

What's an easy way to read random line from a file in Unix command line?

然后做一个grep ... | rl | head -n 1

【讨论】:

    【解决方案2】:

    试试这个:

    DOWNLOADSTRING="$(curl -o - "http://example.com/folder/downloadlinks.txt" | grep "$VARIABLE")" |
        sort -R | head -1
    

    输出将被随机排序,然后第一行将被选中。

    【讨论】:

    • 请注意“|”是命令分隔符(如“;”),因此您不需要行继续符“\”
    • 我想我曾经知道这一点!我这么说是因为我不确定是否需要反斜杠;但我还是把它说出来,以确保。感谢您指出这一点,我将编辑答案。
    【解决方案3】:

    如果mirrors.txt 具有您在问题中提供的以下数据:

    http://alphaserver.com/files/apple.zip
    http://betaserver.com/files/apple.zip
    http://gammaserver.com/files/apple.zip
    http://deltaserver.com/files/apple.zip
    http://alphaserver.com/files/banana.zip
    http://betaserver.com/files/banana.zip
    http://gammaserver.com/files/banana.zip
    http://deltaserver.com/files/banana.zip
    

    然后可以使用以下命令从文件中随机获取一个“匹配字符串”

    grep -E "${VARIABLE}" mirrors.txt | shuf -n1
    

    然后你可以将它存储为变量DOWNLOADSTRING,通过这样的函数调用设置它的值:

    rand_mirror_call() { grep -E "${1}" mirrors.txt | shuf -n1; }
    DOWNLOADSTRING="$(rand_mirror_call ${VARIABLE})"
    

    这将根据用户的${VARIABLE} 输入从文本文件中为您提供一个专用的随机行。这样打字少了很多。

    【讨论】:

      最近更新 更多