DomainsFeatured DomainsFeatured - 10 months ago 41
Linux Question

Reorder Lines Based On Previous File Order Before Randomization

I have the following lines in

file1
:

line 1text
line 2text
line 3text
line 4text
line 5text
line 6text
line 7text


With the command
cat file1 | sort -R | head -4
I get the following in
file2
:

line 5text
line 1text
line 7text
line 2text


I would like to order the lines (not numerically, just the same order as
file1
) into the following
file3
:

line 1text
line 2text
line 5text
line 7text


The actual data doesn't have digits. Any easy way to do this? I was thinking of doing a grep and finding the first instance in a loop. But, I'm sure you experienced guys know an easier solution. Your positive input is highly appreciated.

Answer Source

You can decorate with line numbers, select four random lines lines, sort by line number and remove the line numbers:

$ nl file1 | shuf -n 4 | sort -n -k 1,1 | cut -f 2-
line 2text
line 5text
line 6text
line 7text
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download