0

I have some static data in variable like a table, which has columns, and rows with delimiter character like "|" between them. Example:

Number of row | Name column 1 | Name column 2 | Name column 3
      1       | var of col 1  | var of col 2  | var of col 3
...

I want to get specify row using awk command from my variable:

var="$staticData" | awk '$1=="1" {print}'

When I try to print out this via "echo" I get empty result, but when I using:

echo "$staticData" | awk '$1=="1" {print}'

I get normal result for me.

jpf
  • 1,447
  • 12
  • 22
  • You want to assign your output to the variable `var`? Then this is the way forward: `var="$(echo "$staticData" | awk '$1==1)"`. You can also do `awk '$1==1' <<<"$staticData"` It depends a bit what you actually want to achieve. Please elaborate your question. – kvantour Jul 08 '20 at 11:06

1 Answers1

1

When you run

var="$staticData" | awk '$1=="1" {print}'

you are declaring a variable and redirecting to stdout the result of awk. The variable is store and the output is empty, because the variable is just declared, you did not do anything with it.

When you run

$ staticData='1|2|3|4|5'
$ var="$staticData" | awk '$1=="1" {print}'
$ echo $var

$

It is empty because it has to be. there is nothing in the standard output

When you run

 $ staticData='1|2|3|4|5'
 $ echo $staticData | awk -F '|' '{print $1}'
 1

In my case I redirect the output of the echo to the awk command. You need to understand what redirection and stdout ( standard output ) means in the context of what you are doing.

Roberto Hernandez
  • 8,231
  • 3
  • 14
  • 43