NodeX4
NodeX4

Reputation: 49

error with initiating varibles within an awk command in bash

Goal

I want to iterate over my file with awk which works fine, but when tried to insert my COLOR and WHITE variables.

I realized that I would have to first initialize it within the awk command like so: -v COLOR="${COLOR}" and WHITE="${WHITE}". Yet when I did so I started getting the following error:

awk: warning: escape sequence `\e' treated as plain `e'
awk: cmd. line:1: WHITE=\e[1;37m
awk: cmd. line:1:       ^ backslash not last character on line
awk: cmd. line:1: WHITE=\e[1;37m
awk: cmd. line:1:       ^ syntax error

Full Code

bash.sh

WHITE="\e[1;37m"
COLOR="\e[1;31m"

awk -v COLOR="${COLOR}" WHITE="${WHITE}"  awk -v COLOR="$COLOR" -v WHITE="$WHITE" '
    {
        system("sleep 0.1")
        print "    ("COLOR" NR "WHITE") " $0
    }
' settings.tropx

the settings.tropx file:

some setting
some other setting
set ting
another setting

Final

What is this error referring to and how can I fix it?

Upvotes: 1

Views: 120

Answers (2)

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2855

even if your original shell variables use the \e notation, u can use awk to fix it :

 __w__="${WHITE}" \
 __c__="${COLOR}" \
 mawk '
 BEGIN {  FS = "\\\\\e"
         OFS = "\33" 
       $(ORS = "") = ENVIRON["__w__"]"1"ENVIRON["__c__"]
 print $!(NF = NF) }'



0000000         993090331       829241139       993090331         7156019
         033   [   1   ;   3   7   m   1 033   [   1   ;   3   1   m    
          033 133 061 073 063 067 155 061 033 133 061 073 063 061 155    
         esc   [   1   ;   3   7   m   1 esc   [   1   ;   3   1   m    
           27  91  49  59  51  55 109  49  27  91  49  59  51  49 109    
           1b  5b  31  3b  33  37  6d  31  1b  5b  31  3b  33  31  6d    

0000017

Upvotes: 0

tshiono
tshiono

Reputation: 22032

Would you please try:

#!/bin/bash

WHITE=$'\e[1;37m'
COLOR=$'\e[1;31m'

awk -v COLOR="$COLOR" -v WHITE="$WHITE" '
    {
        system("sleep 0.1")
        print "    ("COLOR NR WHITE") " $0
    }
' settings.tropx

We need to use ANSI quoting $'..' with bash to include an escape sequence. But if you do not have a specific reason to use -v mechanism, you can also say:

awk '
    BEGIN {COLOR="\033[1;31m"; WHITE="\033[1;37m"}
    {
        system("sleep 0.1")
        print "    ("COLOR NR WHITE") " $0
    }
' settings.tropx

Upvotes: 1

Related Questions