Search code examples
linuxubuntucommand-lineprintfshuffle

Print random line into different text file


What I want to do is print a random line from text file A into text file B WITHOUT it choosing the same line twice. So if text file B has a line with the number 25 in it, it will not choose that line from text file A

I have figured out how to print a random line from text file A to text file B, however, I am not sure how to make sure it does not choose the same line twice.

echo "$(printf $(cat A.txt | shuf -n 1))" > /home/B.txt

Solution

  • grep -Fxv -f B A | shuf -n 1 >> B
    

    First part (grep) prints difference of A and B to stdout, i.e. lines present in A but absent in B:

    • -F — Interpret PATTERNS as fixed strings, not regular expressions.
    • -x — Select only those matches that exactly match the whole line.
    • -v — Invert the sense of matching.
    • -f FILE — Obtain patterns from FILE.

    Second part (shuf -n 1) prints random line from stdin. Output is appended to B.