awk command not getting executed in shell script

I am able to execute awk command from shell prompt. but the same command is not getting executed when written and run in a bash script

the command from bash cmd prompt.

awk '/world/{for (i=2; i<NF; i++) printf $i " "; print $NF}1' myfile >tmp$$ ; mv tmp$$ myfile

file:
#  hello world my friend
# this is a beautiful place
$ mary had a little lamb
# jhony jhony yes papa
 
OP
hello world my friend
# this is a beautiful place
$ mary had a little lamb
# jhony jhony yes papa

But the same thing on trying with a bash script, no output is observed
script

#!/bin/bash
#!/usr/bin/awk 
NAME="world"
awk '/$NAME/{for (i=2; i<NF; i++) printf $i " "; print $NF}1' myfile >tmp$$ ; mv tmp$$ myfile

There's two reasons that construct doesn't work - neither within nor without a script:

  • within single quotes shell expansion is not performed - $NAME is taken literally.
  • awk interprets anything between / as a regex constant - again, $NAME will be taken literally.

Use the -v option to awk to hand over parameters, and use the match function in lieu of the /... /

On top, only the shebang in the first line will be interpreted.

Hello Ashima,

In awk value of variables dosn't work like shell ones. Could you please try following and let me know if this helps you.

#!/bin/bash
NAME="world"
awk -vname=$NAME  '{if($0 ~ /name/){for (i=2; i<NF; i++) printf $i " "; print $NF}}1' myfile >tmp$$ ; mv tmp$$ myfile

Let me know if you have any queries.

Thanks,
R. Singh

no, this won't work either for the reasons RudiC explained above.

#!/bin/bash
NAME="world"
awk -vname=$NAME  '$0 ~ name{for (i=2; i<NF; i++) printf $i " "; print $NF}1' myfile >tmp$$ ; mv tmp$$ myfile
1 Like
awk '/world/{for (i=2; i<NF; i++) printf $i " "; print $NF}1' myfile >tmp$$ ; mv tmp$$ myfile

I am afraid that the above command will never produce what you said, but rather the following:

hello world my friend
#  hello world my friend
# this is a beautiful place
$ mary had a little lamb
# jhony jhony yes papa

If your intention is to remove the comment and the spaces in front of any sentence that has the word `world', perhaps sed would be a bit more suitable for it.

#!/bin/bash
NAME="world"
sed "/$NAME/ s/^#[[:blank:]]*//" myfile >tmp$$
mv tmp$$ myfile