system command within awk

I was trying commands within awk. i got stuck here. i take 2 files.

cat input

first
second
third
fourth
fifth
sixth
seventh
eighth
ninht
tenth
cat add

***************
Nirbhay
***************

i run the command

awk '{ if ( NR == 5 ) { print system("cat add") "\n" $0 } else { print } }' input > output

cat output

first
second
third
fourth
***************
Nirbhay
***************
0
fifth
sixth
seventh
eighth
ninht
tenth

My query is that why does 0 appears in the output file, though it is neither in input, nor in add. & what can i do to get rid of it ?

Hi Nirbhay
I think this "0" is the return from the system("cat add") command.

Try this:
awk '{ if ( NR == 5 ) { print system("cat add") 1>/dev/null } else { print }}' input

redirecting return code from system command to null.

Hope this helps.

yes Angad, you're right. But then, using 1>/dev/null inside awk causes a few problems as i can see

awk '{ if ( NR == 5 ) { print system("cat add") 1>/dev/null "\n" $0 } else { print } }' input > output

this simply ignores everything else in the action. here "\n" $0 are ignored. Rest of the line is not printed.

awk '{ if ( NR == 5 ) { print (system("cat add") 1>/dev/null) "\n" $0 } else { print } }' input > output

enclosing in braces gives another problem. i get 1 in the output

first
second
third
fourth
***************
Nirbhay
***************
1
fifth
sixth
seventh
eighth
ninht
tenth

no need to call system to invoke cat. do everything with awk.

# awk 'NR==5{while (( getline line <"add") > 0 ) {print line}}NR!=5' file
first
second
third
fourth
***************
Nirbhay
***************
sixth
seventh
eighth
ninht
tenth

or

# awk 'FNR==NR{a[++d]=$0;next}FNR==5{for(i in a)print a}FNR!=5' add file
first
second
third
fourth
***************
Nirbhay
***************
sixth
seventh
eighth
ninht
tenth

Or simply with sed:

sed '4r add' input

Regards