I have the following example of awk script below according to a prior answer to this question here https://stackoverflow.com/a/69874658/10824251:
awk \
'
FNR==1 {++f}
f==1 {a[i++]=$0}
f==2 {if ($0~/home_cool/) {gsub(/home_cool/, a[int(j++/2)%2]) }; print > "2.txt"}
k==1 {system("echo 'text' && sleep 4")}
f==3 {if ($0~/home_cool/) {gsub(/home_cool/, a[int(k++/2)%3 + 2]) }; print > "3.txt"}
k==1 {system("echo 'text2' && sleep 4")}
f==4 {if ($0~/home_cool/) {gsub(/home_cool/, a[int(k++/2)%3 + 2]) }; print > "4.txt"}' \
1.txt 0.txt 0-1.txt 0-2.txt
I am trying to add a command shell only one time run after creating the 2.txt file and before creating the 3.txt file.
This means that the specific shell command should only be executed after the 2.txt file has been fully created.
The solution should also be able to print text2 before 4.txt to be created.
I am using system(), my attempt so far it does not work well and the only thing that does not work is that the shell script is performed 3 times rather than 1 (this can be seen with the 3 text prints on the screen).
What can I do to see what really misses to solve this and echo 'text' is run only once and before 2.txt be created?
I tried to insert a counter (without while) inside system() (system("counter=0; if [[ "$counter" -gt 2 ]] then echo "text" fi; sleep 4")) but did not work, and it really does not make much sense because counter=0 should be out of system() I believe.
Note to Clarify Choice of Answer with Solved Status :
Doubt complex and cruel, choose which answer I will give as solved:
On the one hand the simplicity that explains a lot on the own account of the user @dan answer (author's answer to the previous issue of the file number in awk);
On the other hand a answer with a very useful deepening for learning from user @markp-fuso.
Maybe I should think about other users when they need to read this issue, so I'll choose how solved the issue of markp-fuso. I hope to understand all the authors of answers to this issue.
I am trying to add a command shell only one time run after creating the 2.txt file and before creating the 3.txt file.
Add a test for FNR==1, as the very first command of the f==3 block, like so:
f==3 {if (FNR==1) {system("##")}; if ($0~/home_cool/) {gsub(/home_cool/, a[int(k++/2)%3 + 2]) }; print > "3.txt"}
It will be executed before anything else in that block.
Alternatively, you can add this pattern {action}, directly above f==3:
f==3 && FNR==1 {system("##")}
f==3 {if ($0~/home_cool/) {gsub(/home_cool/, a[int(k++/2)%3 + 2]) }; print > "3.txt"}
The pattern/action blocks are always executed in the order given, so again, it will execute first.
Whichever you think is more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With