[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: help with mawk



On Thu 18 Mar 2004 16:53:58 +0000(-0800), gcrimp@vcn.bc.ca wrote:
> On Thu, Mar 18, 2004 at 06:19:43PM +0100, Joachim Fahnenmueller wrote:
> > Hi ghcbc,
> > 
> > VARIABLENAME=$(mawk 'whatever') .
> 
> Hi,
> 
> Thanks.  I can get this to work on the command line, but not in a bash
> script.

I think the original question was how to strip / characters from a 
variable in a shell script. Assuming it's a bash script you can do it 
like this:

	that=some/reasonable/path/name
	this=${that//\//}


If you want to do it with awk:

> If I make a function _foobar as follows and call it with "_foobar
> some/reasonable/path/name" from within the script
> 
> function _foobar  () {
> 
>   local symbolicname=""
> 
>   echo -e "\nBefore statement \$symbolicname = $symbolicname"
> 
>   symbolicname=$(mawk 'gsub("/","",$1) { print }')
> 
>   echo -e "\nAfter statement \$symbolicname = $symbolicname"
> }
> 
> I get as output
> 
> 	Before statement $symbolicname = 
> 
> 	After statement $symbolicname =
> 
> :(
> 
> Do you know what I might do to get this going in the script?

1. You didn't give mawk any input.

2. The third argument to gsub is the name of an awk variable to modify.
   In this case it's $1 which is the first field of the input line (which
   is empty because there's no input).

3. I suspect you meant $1 to be the first argument to function _foobar,
   but it's not because the shell doesn't expand $ inside '', you need
   to use "" instead.

Try this:
	symbolicname=$(echo "$1" | mawk 'gsub("/","") { print }')


> > BTW: Your syntax seems strange to me. AFAIK it should be something like
> > mawk '/pattern/ {action}'
> > (see man mawk).
> 
> Got what I have straight from man mawk (tempered slightly by "Unix power
> tools") :)
> /pattern/ = gsub("/","",$1)
> {action}  = {print}
> 
> gsub(a,b,c), global substitution, will replace all instances of a with b in
> the input record c, or stdin if c is omitted.

Using gsub in the pattern means that the action is only executed if gsub 
made one or more substitutions, i.e. nothing is printed if the input 
contains no / characters. If you want an output for every input, try this:

        symbolicname=$(echo "$1" | mawk '{ gsub("/",""); print }')

Note there's no pattern so everything matches.

-- 
Cheers,
Clive



Reply to: