Michael
Michael

Reputation: 5

awk read from multi variables instead of files

I have two variables $name and $birthday

$> echo "$name"
Mack
Lee

$> echo "$birthday"
3rd 
May

I want to get output like this:

Mack  1 1
Lee  2 2
3rd  3 1
May 4 2

but,I enter the command:

$> echo -e "$name" "\n" "$birthday"|awk '{print $0,NR,FNR}'

And get this:

Mack  1 1
Lee  2 2
 3rd  3 3   ###here a space in the first
May 4 4

How can I remove the leading spaces and get expect FNR values?

Upvotes: 0

Views: 399

Answers (3)

uwalakab
uwalakab

Reputation: 1

Using the "Bash process substitution" worked for me. Many thanks. I'm using variables instead of files as I now no longer need to clean up workspace files under /tmp that I was using before. Also am using 2 data inputs to "awk" to join 2 tables of data. "awk" arrays have a dynamic index method, where it does not always have to be [0] for the 1st element, 1 for the 2nd etc. You can use individual values like a key field in a database table.

Upvotes: 0

hradecek
hradecek

Reputation: 2513

Just use process substitution:

$ awk '{print $0,NR,FNR}' <(echo -e "$name") <(echo -e "$birthday")

This should solve both problems, empty space and FNR values. This basically passes two inputs into the awk, just like passing two input files.

Upvotes: 2

tripleee
tripleee

Reputation: 189387

Technically you can use a Bash process substitution. Each command in <(cmd) is exposed as a filehandle-like object to Awk and other processes.

awk '{print $0,NR,FNR}' <(echo "$name") <(echo "$birthday")

This really begs the question what you are actually hoping to accomplish, though. Having nontrivial amounts of data in shell variables is usually a symptom of a more fundamental design problem.

Upvotes: 2

Related Questions