tags:

views:

281

answers:

2

I am using the below code to change an existing awk script so that I can add more and more cases with a simple command.

echo `awk '{if(/#append1/){print "pref'"$1"'=0\n" $0 "\n"} else{print $0 "\n"}}' tf.a

note that the first print is "pref'"$1"'=0\n" so it is referring to the variable $1 in its environment, not in awk itself.

The command ./tfb.a "c" should change the code from:

BEGIN{
#append1
}
...

to:

BEGIN{
prefc=0
#append1
}
...

However, it gives me everything on one line.

Does anyone know why this is?

+2  A: 

do it like this. pass the variable from shell to awk properly using -v

#!/bin/bash
toinsert="$1"
awk -v toinsert=$toinsert '
/#append1/{
    $0="pref"toinsert"=0\n"$0
}
{print}
' file > temp
mv temp file

output

$ cat file
BEGIN{
#append1
}

$ ./shell.sh c
BEGIN{
prefc=0
#append1
}
ghostdog74
Still doesn't work. Same problem.
piggles
Does it matter if `awk` is wrapped in `echo`?
piggles
lose the echo and try again. seriously, i don't know what is the echo for. See my output. Otherwise, show more details of your code and describe what you want clearly.
ghostdog74
@Mechko: the echo is what's causing the output to print on one line. Eliminate it as **ghostdog74** suggests or do something like this: `echo "$(awk stuff)"` - wrapping it in double quotes will preserve the newlines.
Dennis Williamson
ah ok. I do need the echo because there's a bunch of other things that need printing out.btw, I now have a fully functional markdown parser with the option to have users define their own markdown macros, if anyone wants it. I'm going to work on an installation script tomorrow.
piggles
+2  A: 

If you take awk right out of the equation you can see what's going on:

# Use a small test file instead of an awk script
$ cat xxx
hello
there
$ echo `cat xxx`
hello there
$ echo "`cat xxx`"
hello
there
$ echo "$(cat xxx)"
hello
there
$

The backtick operator expands the output into shell "words" too soon. You could play around with the $IFS variable in the shell (yikes), or you could just use double-quotes.

If you're running a modern sh (e.g. ksh or bash, not the "classic" Bourne sh), you may also want to use the $() syntax (it's easier to find the matching start/end delimiter).

Gordon Broom