variable expansion inside awk command

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
Daniel Santos [ Mi, 17 Oktober 2007 14:25 ] [ ID #1846765 ]

Re: variable expansion inside awk command

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
Stephane CHAZELAS [ Mi, 17 Oktober 2007 15:49 ] [ ID #1846766 ]

Re: variable expansion inside awk command

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
cichomitiko [ Mi, 17 Oktober 2007 16:06 ] [ ID #1846767 ]

Re: variable expansion inside awk command

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 <xxx [at] example>, (Friedhelm Waitzmann) xxx [at] example,
"Waitzmann, Friedhelm" <xxx [at] example>
Friedhelm Usenet Wait [ Di, 06 November 2007 21:48 ] [ ID #1863327 ]
Linux » comp.unix.shell » variable expansion inside awk command

Vorheriges Thema: How to autocomplete in shell
Nächstes Thema: background and foreground process