击。如何将文本文件中的随机行分配给变量? [重复]

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

这个问题在这里已有答案:

我有包含许多行的文本文件。我需要去做:

  1. shuf txt.txt
  2. 从shuf输出读取第一行到变量$ line

如何用bash脚本在一行中表示它?

现在它是这样的:

shuf txt.txt -o aaa.txt
n=$(head -n 1 aaa.txt)
rm -rf aaa.txt

你可能会注意到,它不是很好

bash text variable-assignment
2个回答
0
投票

您可以使用shuf轻松完成此操作:

n=$(shuf -n1 file)

https://www.gnu.org/software/coreutils/manual/html_node/shuf-invocation.html

有关堆栈overflow.com的相关问题:What's an easy way to read random line from a file in Unix command line?


0
投票

听起来像是家庭作业。这里有一些提示。

将变量分配给命令的结果:

x=`command`

管道分配:

x=`command1 | command2`

将command1的第一行输出分配给变量:

x=`command1 | head -n1`
© www.soinside.com 2019 - 2024. All rights reserved.