variable expansion inside awk command

variable expansion inside awk command

am 17.10.2007 14:25:47 von Daniel Santos

Hello!

How do I make awk print a multi line shell variable ?

I did (on the cmd line):

prompt# TEXT="word1
> word2"
# awk "{ print \"$TEXT\" }"
which in turn complains of the unterminated {

How could I do it in awk ?
Daniel Santos

Re: variable expansion inside awk command

am 17.10.2007 15:49:40 von Stephane CHAZELAS

2007-10-17, 12:25(+00), Daniel Santos:
> Hello!
>
> How do I make awk print a multi line shell variable ?
>
> I did (on the cmd line):
>
> prompt# TEXT="word1
>> word2"
> # awk "{ print \"$TEXT\" }"
> which in turn complains of the unterminated {
>
> How could I do it in awk ?

awk '
BEGIN {
text = ARGV[1]
print text
exit
}' "$TEXT"

You could also do

awk -v text="$TEXT" '
BEGIN {
print text
}'

but beware the awk expands backslash sequences like \n, \r,
\t...

TEXT='\text\'
awk -v text="$TEXT" '
BEGIN {
print text
}' | cat -t

outputs:

^Iext\

--
Stéphane

Re: variable expansion inside awk command

am 17.10.2007 16:06:14 von cichomitiko

Stephane CHAZELAS wrote:
> 2007-10-17, 12:25(+00), Daniel Santos:
[...]
>> How do I make awk print a multi line shell variable ?
>>
>> I did (on the cmd line):
>>
>> prompt# word1
>>> word2"
>> # awk "{ print \"$TEXT\" }"
>> which in turn complains of the unterminated {
>>
>> How could I do it in awk ?
[...]
> You could also do
>
> awk -v text="$TEXT" '
> BEGIN {
> print text
> }'
[...]

Not with all awks:

$ what /usr/bin/nawk
/usr/bin/nawk:
SunOS 5.9 Generic 117067-04 May 2006

$ what /usr/xpg4/bin/awk
/usr/xpg4/bin/awk:
SunOS 5.9 Generic May 2002


$ t='a
> b'
$ nawk -v text="$t" '
> BEGIN {
> print text
> }'
nawk: newline in string a... at source line 1


$ /usr/xpg4/bin/awk -v text="$t" '
> BEGIN {
> print text
> }'
/usr/xpg4/bin/awk: file "Segmentation Fault (core dumped)



Dimitre

Re: variable expansion inside awk command

am 06.11.2007 21:48:50 von Friedhelm Usenet Waitzmann

Use the environment to present the string to awk:

$ text='word1
word2'
$ env MY_TEXT="$text" awk '{ print ENVIRON["MY_TEXT"]; }'

--
Bitte in die Adressierung auch meinen |Please put my full name also into
Vor- u. Nachnamen stellen z.B. |the recipient like
Friedhelm Waitzmann , (Friedhelm Waitzmann) xxx@example,
"Waitzmann, Friedhelm"