bash, (g)awk, local variables
Colin Law
clanlaw at googlemail.com
Sat Jun 30 16:33:53 UTC 2012
On 30 June 2012 17:21, MR ZenWiz <mrzenwiz at gmail.com> wrote:
> On Sat, Jun 30, 2012 at 6:13 AM, Colin Law <clanlaw at googlemail.com> wrote:
>> On 30 June 2012 14:03, franz.reitinger <franz.reitinger at htl-wels.at> wrote:
>>> Hi,
>>> I'm using awk for string manipulations within a (backup)bash script. Among
>>> others I have to do some kind of substring operations using the built-in
>>> index-function:
>>>
>>> Docu:
>>> index(in, find)
>>> This searches the string in for the first occurrence of the string find, and
>>> returns the position in characters where that occurrence begins in the
>>> string in. For example:
>>>
>>> awk 'BEGIN { print index("peanut", "an") }'
>>>
>>> Of course this example works; however I want to replace both literals with
>>> the content of local bash / environment variables like:
>>>
>>> a= $(cat ANY_FILE);
>>> b="anyString"
>>>
>>> awk 'BEGIN { print index($a, $b) }'
>>>
>>> Where I'm wrong & how can I use bash variables within built-in functions of
>>> awk?
>>
>> I am not an expert but if in a terminal I do
>> a = "a string"
>> echo $a
>> then I see
>> a string
>> as expected. However if I do
>> echo '$a'
>> then I see
>> $a
>>
>> but echo "$a" shows a string. So I suggest trying double quotes in
>> your awk command.
>>
>
> Not quite.
That is very generous, I think a better description of my post would
be 'a load of twaddle' :)
Colin
>
> All '$' references inside awk are to its own variables, usually
> (always?) just the positional variables for the elements in the input
> line (i.e., $0 = the whole line, $1 is field #1, etc). If you put a $
> in front of a variable name, it will attempt to access that element in
> the input line (i.e., if the variable 'field' == 1, then $field is
> equivalent to $1).
>
> To send in variable values from outside awk, you need to define them
> on the command line:
>
> awk -v mybash_a=$a -v mybash_b=$b '<awk script>'
>
> and inside the awk script, you do NOT use $ to access the variables,
> just their names. In this case, use 'mybash_a' to access the value of
> your bash $a variable, etc.
>
> Cheers.
>
> MR
More information about the ubuntu-users
mailing list