Home > Enterprise >  Is there a way to use the less command in a while loop?
Is there a way to use the less command in a while loop?

Time:04-25

I have this while loop that takes an input and creates a printf for each entry. This file is really big so having it print out will take forever. Is there a way I can save the result to a file and use less to have it be a paginated output?

while read line
do
            id=$(cut -d' ' -f1 <<< $line)
            ip=$(cut -d' ' -f2 <<< $line)
            mon=$(cut -d' ' -f3 <<< $line)
            day=$(cut -d' ' -f4 <<< $line)

            printf "%s 45%s (%s %s)\n" "$id" "$ip" "$mon" "$day"
done <<< "$inputFile"

I tried this

result =$("%s 45%s (%s %s)\n" "$id" "$ip" "$mon" "$day")

and then just doing

less "$result"

outside the loop but that didn't work and I don't know where to go from here.

CodePudding user response:

*nix is all about streaming tools. One tools streams to another. if you want to watch your script run using less you can just 'pipe' it...

write your script to a file - we'll call it "my.script.sh", make it executable "chmod x my.script.sh" then use the | (pipe) operator...

./my.script.sh | less

CodePudding user response:

As Gordon said, this is a lot of pointless work, especially if the file is going to be big. Also <<< "$inputFile" implies the entire text of the file you said was so big has already been read into the inputFile variable, which seems pointless and counterproductive unless there's some specific reason?

Try something like this -

awk '{printf "%s 45%s (%s %s)\n", $1, $2, $3, $4}' file.in | less

or if you want the output saved in a file AND paginated to the screen,

awk '{ printf "%s 45%s (%s %s)\n", $1, $2, $3, $4 }' file.in | tee out.txt | less
  

I also agree with Clint. The pagination should probably be separate - but since I haven't seen the whole structure, try a few and see what works.

  • Related