LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Setting variables in awk according to matching pattern (https://www.linuxquestions.org/questions/linux-newbie-8/setting-variables-in-awk-according-to-matching-pattern-4175703026/)

Faki 11-03-2021 10:33 AM

Setting variables in awk according to matching pattern
 
How can I construct a pattern in `awk` then seh a value for a variable.

I would like to match the following patterns

Code:

^[[:space:]]*(#;!)+[[:space:]]*Mode: org$

^[[:space:]]*(//|@c)[[:space:]]*Mode: org$


pan64 11-03-2021 10:34 AM

why do you open a new thread for this?
Code:

/pattern/ { var=value }

Faki 11-03-2021 11:15 AM

Basically to make the task simpler rather than reading through a lot of things.

Turbocapitalist 11-03-2021 01:07 PM

Or throw in a logical OR using the || operator.

Code:

/^[[:space:]]*(#;!)+[[:space:]]*Mode: org$/ \
|| /^[[:space:]]*(\/\/|@c)[[:space:]]*Mode: org$/ \
{ var=value }

Note that inside the pattern the slashes must be escaped.

Faki 11-03-2021 10:57 PM

Why does it not work like this?

Code:

charcl='^[[:space:]]*([#;!]+|@c|\/\/)[[:space:]]*'
 awk -v ccls="$charcl" \
    found { sub(/ccls/,""); print }' "$efile"

But I was unable to remove the comment characters.

Turbocapitalist 11-03-2021 11:08 PM

Please show the AWK script in which that line is to be found so that the context is known.

Faki 11-04-2021 12:18 AM

Code:

capture ()
{
 local efile="$1"
 
 local begorg endorg charcl

 charcl='^[[:space:]]*([#;!]+|@c|\/\/)[[:space:]]*'
 begorg="${charcl}"'Mode: org$'
 endorg="${charcl}"'# End of org$'
 
 awk -v ccls="$charcl" -v bego="$begorg" -v endo="$endorg" \
  '$0 ~ bego { found=1; next }
    $0 ~ endo { found=0; }
    found { sub(/ccls/,""); print }' "$efile"
}

Have also used

Code:

charcl='^[[:space:]]*([#;!]+)[[:space:]]*'
But the comment characters are not being removed.

pan64 11-04-2021 01:18 AM

when you use sub with a variable you must not use / :
Code:

found { sub(ccls,""); print }

Faki 11-04-2021 02:03 AM

Works very well, thank so very much. Is there a way to add an empty line between blocks (one block is identified by the lines enclosed within `begorg` and`endorg`)?

Turbocapitalist 11-04-2021 02:16 AM

Yes, it would be with a print() or printf() function. Add that to the appropriate stanza.

Faki 11-04-2021 05:26 AM

Have used `print ""` to print a blank line. Introduced it on the line checking `endrsc`.

Code:

$0 ~ endrsc { insc=0; print "" }


All times are GMT -5. The time now is 11:26 AM.