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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With