简体   繁体   中英

selecting random line from text file after deleting empty lines

I have a text file which contains empty lines, I want to select a line except an empty line. Therefore, I tried to remove empty lines, select a random line and write into a text file. The file is like;

aaaa

bbbb


cccc

And output should be like;

bbbb

I can remove the empty lines using:

sed '/^\s*$/d' input.txt

And I can select a random line using:

echo $(shuf -n 1 input.txt) > output.txt

However, I cannot bring them together I used this, but did not work.

echo $(shuf -n 1 $(sed '/^\s*$/d' input.txt)) > output.txt

It gives an error for the second word of the line as shuf: extra operand 'someWord'

Any help needed, thanks!

Where does the output of your first sed command go? Based on what you have, it goes to stdout. It is definitely going to stdout within the $(...) sub-process. This means they are written straight out to the outer sub-process as command line arguments.

The shuf command is trying to get something from stdin, not arguments from the command line.

What might work (I have not tried this), is to pipe. Try this

sed '/^\s*$/d' input.txt | shuf -n 1 >output.txt

Hope this helps

You need to do a shell redirection, not a shell substitution:

echo $(shuf -n 1 <(sed '/^\s*$/d' input.txt)) > output.txt

In any case, that can be simplified a lot:

sed '/^\s*$/d' input.txt | shuf -n 1 > output.txt

您可以为此使用单个awk命令:

awk 'BEGIN{srand()} NF{row[++n]=$0} END{print row[int(rand() * n+1)]}' file

一种解决方案:

grep -v  '^$'  file | shuf -n 1 > output.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM