LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   script question (https://www.linuxquestions.org/questions/programming-9/script-question-350551/)

therealbxp 08-06-2005 09:00 AM

script question
 
hello i want to search the startposition of some text but i have some problem with inserting the variable into the awk statement
the textlijn variable is filled with some text



textlijn=`head -n $file_length2 pics.txt | tail -n 1`


startpos=`expr awk 'BEGIN { print index("'$textlijn'", "changeModelePic") }' + 0 `
here is something fishy but what=====^^^^^^^^

thanx in advance
greeting bert

acid_kewpie 08-06-2005 09:21 AM

fishy? did you trying learning awk in the first place? you need to explicitly pass variables into a an awk script:
Code:

awk -v awkxyx=$xyz 'BEGIN awkxyz++ etc...'

therealbxp 08-06-2005 09:39 AM

acid_kewpie i am just starting
can you give me more information on the code you provided or point me in the right way ( example)

thx for replying

carl.waldbieser 08-06-2005 12:12 PM

The "-v" option to awk has to come before the actual awk program. It lets you associate a variable name with a given value inside the program. For example:

Code:

$ awk -v magic="xyzzy" 'BEGIN {print magic}' *
This tells awk that inside the program you give it, the variable "magic" will have the value "xyzzy".

Incidently, the reason your technique will not work is because the awk program itself is the part of the command line in single quotes. Single quotes on the command line turn off the meanings of most special characters like $. You cannot expand variables in single quotes.

You can also use ENVIRON inside an awk program:

Code:

awk 'BEGIN {print ENVIRON["HOME"]}' *
This lets you access shell variables.

therealbxp 08-06-2005 02:19 PM

carl.waldbieser thx
thats realy clear explaind
the rest i will find out myself
thx Bert

btw here is the solution ( if someone need it in the future)
startpos=`awk -v magic="$textlijn" 'BEGIN { print index(magic, "changeModelePic") }'`

eddiebaby1023 08-07-2005 04:28 AM

Re: script question
 
Quote:

Originally posted by therealbxp
hello i want to search the startposition of some text but i have some problem with inserting the variable into the awk statement
the textlijn variable is filled with some text



textlijn=`head -n $file_length2 pics.txt | tail -n 1`


startpos=`expr awk 'BEGIN { print index("'$textlijn'", "changeModelePic") }' + 0 `
here is something fishy but what=====^^^^^^^^

thanx in advance
greeting bert

The answer is to learn how to do shell quoting properly, then you won't have to mess about with awk variables.
Code:

startpos=`expr awk "BEGIN { print index(\"$textlijn\", \"changeModelePic\") }" + 0 `
I haven't tested this, let me know if and how it doesn't work and I'll fix it.


All times are GMT -5. The time now is 09:51 AM.