在分隔符上拆分标准输出并随机选择行?

在分隔符上拆分标准输出并随机选择行?

如何在分隔符上分割命令的输出(在本例中为新行),然后随机选择一行?

我想做的一个例子是:

curl -s http://www.compciv.org/files/pages/nyt-sample/ | pup 'article p text{}' \
        | sed 's/^[ \r\n\t]*//'

其输出:


The fine of $35 million in each of two civil penalties, for a total of $70 million, is a record for the National Highway Traffic Safety Administration.


After becoming a grandmaster at the tender age of 13, Sam Sevian is getting some help from the chess champion Garry Kasparov.


In a small stand against gentrification, the nonprofit Wildflowers Institute has helped San Francisco’s gritty Tenderloin neighborhood define its cultural assets.


The currency has fallen because investors fear that the eurozone is stuck in a quagmire and its leaders are not doing much to pull it out.


President Obama is facing opposition from his party to one of his top priorities: winning the power to negotiate international trade pacts and speed them through Congress.

我怎样才能分割换行符,然后只选择一个,这样我就会得到类似的东西

The currency has fallen because investors fear that the eurozone is stuck in a quagmire and its leaders are not doing much to pull it out.

答案1

简单的答案是将您的命令通过管道传输到shuf -n1.这将输入(行)转换为随机顺序,然后输出其中之一(即随机选择)。

但是你的 ( curl … | pup …) 命令输出空行。我猜您不想在最终输出中得到这些空行之一。  shuf 似乎没有忽略空行的选项;您必须先将其删除才能 shuf看到它们。通用方法是

卷曲 -s http://www.compciv.org/files/pages/nyt-sample/ | pup '文章 p 文本{}' \
        | sed 's/^[ \r\n\t]*//'| grep '.'    |舒夫-n1

但是,由于您现有的命令行已经以命令结尾sed,我们可以利用它:

卷曲 -s http://www.compciv.org/files/pages/nyt-sample/ | pup '文章 p 文本{}' \
        |sed -e 's/^[ \r\n\t]*//' -e '/^$/d'|舒夫-n1

\nPS 将其包含在您的中是没有意义的sed s命令 -sed一次处理一行输入,除非你告诉它否则,并且行永远不会包括 \n

相关内容