Stephan K.
Stephan K.

Reputation: 15702

Bash script to sort input file before piping to while loop

I have this bash script:

while IFS='"' read -r a ip c
do
    echo "ip: $ip"
    whois "$ip" | grep netname
done < <(head -10 file.log)

How can I sort the file.log file (e.g. with sort -n -r) before the first ten lines are taken and handed over to the while-loop?

Upvotes: 0

Views: 2288

Answers (2)

Arnab Nandy
Arnab Nandy

Reputation: 6702

Use this command,

sort -nr file.log | head -10

Upvotes: 0

fedorqui
fedorqui

Reputation: 289725

If you want to get the top 10 lines after sorting, just sort it before using head:

while IFS='"' read -r a ip c
do
    echo "ip: $ip"
    whois "$ip" | grep netname
done < <(sort file.log | head -10)
         ^^^^^^^^^^^^^^^

Apply the sort flags you require, of course.

Upvotes: 3

Related Questions