Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a command for each loop in awk?

I'm using awk to split a binary stream and I can get each part into a for loop like this.

for(i=1;i<=NF;i++)

I don't want to convert each field to text or arguments, but simply pass it directly to a command.

I'm trying to find something like this,

for(i=1;i<=NF;i++) system("decode")

but this obviously doesn't work. decode receives no input.

How do I get decode to receive each field in the loop?

like image 471
akula1001 Avatar asked Aug 19 '17 16:08

akula1001


People also ask

Can you use for loop in awk?

There are two kinds of for loops in awk. One kind of for loop initializes a variable, performs a test, and increments the variable together, performing commands while the test is true. Another kind of for loop sets a variable to successive indices of an array, performing a collection of commands for each index.

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

How do you iterate through an awk array?

for-in loop is used here to iterate each index from the array and print the customer's name. Run the script from the terminal. Output: The following output will appear after executing the script.


2 Answers

Doesn't this works for you?

for(i=1;i<=NF;i++) print $i | "decode"
close("decode")

It sends each field (or byte in your case) to a pipe connected to the "decode" program.

After that, close the "decode" pipe to force a flush of all the data on that pipe.

You can read more about gawk redirection on https://www.gnu.org/software/gawk/manual/html_node/Redirection.html

If you want to execute "decode" for each single byte, just close the pipe in each iteration:

for(i=1;i<=NF;i++) {
    print $i | "decode"
    close("decode")
}
like image 177
valrog Avatar answered Jan 02 '23 18:01

valrog


Is this what you are trying to do?

awk '{for(i=1; i<=NF; i++) system("decode "$i)}' input_file.txt

This should pass each field, contained in awk variable $i, to the decode external program. Mind the variable is outside the quotes for "decode ", or it would be interpreted by the shell instead of awk.

like image 22
Qeole Avatar answered Jan 02 '23 18:01

Qeole