user2886545
user2886545

Reputation: 713

Matching a variable with AWK

this is my code:

awk -v header=$header '{if($0~/header/){if(i>0){printf "\n"$0}else{printf $0}}else{printf "\t"$0};i++}END{printf "\n"}' $1 > $basename1"_tab.tab"

However, it maches exactly 'header'' instead of the content of the variable. For example, if I set header='hola', I want the script to match hola instead of header.

Do you have any idea?

Thanks in advance.

Upvotes: 0

Views: 113

Answers (3)

Kent
Kent

Reputation: 195029

try this:

awk -v head="$header" '{if($0~head){if(i>0){printf "\n"$0.....

Upvotes: 0

Rahul Patil
Rahul Patil

Reputation: 1034

You can use double quotes to use shell variable

Example 1#:

rahul@test-srv:~$ u=root
rahul@test-srv:~$ awk "/$u/" /etc/passwd
root:x:0:0:root:/root:/bin/bash

Example 2#

rahul@test-srv:~$ r=rahul
rahul@test-srv:~$ awk  '/'"$r"'/' /etc/passwd
rahul:x:1000:1000:rahul,,,:/home/rahul:/bin/bash

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207365

That is weird. If you change header to h it works!

header=hola; echo hola | awk -v h=$header '/h/{print "Matched"}'
Matched

header=hola; echo hola | awk -v header=$header '/header/{print "Matched"}'

And Kent's doesn't seem to work - which is definitely not what I would expect!!!

header=hola; echo hola | awk -v header="$header" '/header/{print "Matched"}'

Upvotes: 0

Related Questions