当前位置: 动力学知识库 > 问答 > 编程问答 >

bash grep 'random matching' string

问题描述:

Is there a way to grab a 'random matching' string via bash from a text file?

I am currently grabbing a download link via bash, curl & grep from a online text file.

Example:

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

from online text file which contains

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

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

where $VARIABLE is something the user selected.

Works great, but i wanted to add some mirrors to the text file.

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

the code should pick a random 'banana' string and store it as the 'DOWNLOADSTRING' variable.

the current code above can only work with 1 string in the text file, since it grabs everything 'banana'.

What this is for; i wanted to add some mirror downloadlinks for the files in the online text file, and the current code doesn't allow that.

Can i let grep grab one random 'banana' string? (and not all of them)

网友答案:

See this question to see how to get a random line after grep. rl seems like a good candidate

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

then do a grep ... | rl | head -n 1

网友答案:

Try this:

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

The output will be random-sorted and then the first line will be selected.

分享给朋友:
您可能感兴趣的文章:
随机阅读: