Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actual bash string storing awk source [closed]

Tags:

bash

awk

I have been calling awk commands from bash using the customary single quotes. How can one use an actual string to store the awk source, then introduce that to tho awk command later?

printf '%s\n' "$@"  \
  | awk -v frg="$ctp" -v rst="$sgr" -v prl="$rl"  \
    '{ if ( $0 ~ prl ) {
         fm = "%s%s%s\n" ; printf(fm, frg, $0, rst) }
       else {
         fm = "%s\n" ; printf(fm, $0) }
     }'

The change would be

str="
{ if ( $0 ~ prl ) {
    fm = "%s%s%s\n" ; printf(fm, frg, $0, rst) }
  else {
    fm = "%s\n" ; printf(fm, $0)
   }
}"

Then I would perhaps call the command with

printf '%s\n' "$@"  \
  | awk -v frg="$ctp" -v rst="$sgr" -v prl="$rl" "$str"
like image 881
Dilna Avatar asked Jun 09 '26 14:06

Dilna


1 Answers

Without more info on the problem you're trying to solve - don't store code in a string, use a function:

foo() {
  awk -v frg="$ctp" -v rst="$sgr" -v prl="$rl"  \
    '{ if ( $0 ~ prl ) {
         fm = "%s%s%s\n" ; printf(fm, frg, $0, rst) }
       else {
         fm = "%s\n" ; printf(fm, $0) }
     }'
}

printf '%s\n' "$@"  \
  | foo

or:

foo() {
  awk -v frg="$1" -v rst="$2" -v prl="$3"  \
    '{ if ( $0 ~ prl ) {
         fm = "%s%s%s\n" ; printf(fm, frg, $0, rst) }
       else {
         fm = "%s\n" ; printf(fm, $0) }
     }'
}

printf '%s\n' "$@"  \
  | foo "$ctp" "$sgr" "$rl"

or similar.

That way you encapsulate the functionality you want from your awk script while avoiding tightly coupling your shell script to your awk script.

like image 104
Ed Morton Avatar answered Jun 11 '26 22:06

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!