0

While trying to combine output of apt-get search and apt-get policy, I have created this following script.

apt-cache search zsh | \
tee file1 | awk '{ print $1 }' | \
while read file; do apt-cache policy $file | awk 'FNR==2{print $0}' >> file2; done; \
paste file1 file2 | cat

It seems to be logically correct to me but the output is wrong. I begin to test outputs command by command and saw that doing wc of file file2 returns 1353 lines

apt-cache search zsh | \
tee file1 | awk '{ print $1 }' | \
while read file; do apt-cache policy $file | awk 'FNR==2{print $0}' >> file2; done; \
cat file2 | wc -l

but wc just after the first line returns 123 lines

apt-cache search bash | wc -l

So while loop was never fetched 1353 lines of output, yet it processes that.

I was expecting the output like

zgen - Lightweight plugin manager for ZSH inspired by Antigen    Installed: (none)
zplug - next-generation plugin manager for zsh                   Installed: (none)
zsh - shell with lots of features                                Installed: <version>
.
.
.

Is the logic of my script wrong?

Where am I making the mistake here?

Edit: The script given by Steeldriver in the comments below is working fine but could someone please explain what's wrong with the above script

  • 2
    Are you remembering to truncate or remove file2 between runs? Regardless, you can do the whole thing with a single read and a single awk I think e.g. apt-cache search zsh | while read -r pkg desc; do apt-cache policy "$pkg" | awk -v pkg="$pkg" -v desc="$desc" 'NR==2 {print pkg, desc, $0}'; done – steeldriver Jul 1 '17 at 10:33
  • @steeldriver Thanks, your script runs exactly how I wanted, but I am still not able to understand what problem is there with my scirpt. Why would I need to truncate file2 when I am already passing truncated content of apt-cache search to the while loop using awk '{ print $1 }' command in the second pipe – GypsyCosmonaut Jul 1 '17 at 19:08
  • 1
    You are appending to file2 eac time you run your code; assuming that you've tested it a few times then file2 will contain the results of all the previous runs unless you truncate it (> file2) or remove it (rm file2) between runs – steeldriver Jul 1 '17 at 21:35
  • @steeldriver Got it, thank you so much for helping.... <3 <3 – GypsyCosmonaut Jul 1 '17 at 23:14
  • @steeldriver Please post that as an answer so the OP can accept. – tripleee Jul 2 '17 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.