L. Quastana
L. Quastana

Reputation: 1336

Awk does not return what i want

I have this Awk :

ligne_padd=$(echo $ligne_padd | awk 'BEGIN {FIELDWIDTHS="11 105 105"}{if ($2 ~ /^\s*$/) $2 = "XXXXX"; if ($3 ~ /^\s*$/) $3 = "XXXXX"; $1=substr($1,1,7)0substr($1,9); printf "%-11s%-105s%-105s\n", $1,$2,$3}')

I have a positionnal file structured like that:

ID(11c),NAME(105c),CITY(105c)

I want to format the fields like that :

ID_out = ID(1,7) + 0 + ID(9)

NAME_out = If NAME is empty or with blanks ? XXXXX

CITY_out = If CITY is empty or with blanks ? XXXXX

For this input :

AAAAAAAAXXXKBB BBBBB AD                                                                                             BEOGRAD 

I have this out put :

AAAAAAA0XXXKBB BBBBB BB BEOGRAD                                                                                     XXXXX 

And i want :

 AAAAAAA0XXXKBB BBBBB AD                                                                                             BEOGRAD 

Upvotes: 1

Views: 83

Answers (2)

Håkon Hægland
Håkon Hægland

Reputation: 40718

Your code:

BEGIN {
    FIELDWIDTHS="11 105 105"
}
{
    if ($2 ~ /^\s*$/) 
        $2 = "XXXXX"
    if ($3 ~ /^\s*$/)
        $3 = "XXXXX"
    $1=substr($1,1,7) "0" substr($1,9)
    printf "%-11s%-105s%-105s\n", $1,$2,$3
}

works for me.. That is, it produces the expected output:

AAAAAAA0XXXKBB BBBBB AD                                                                                             BEOGRAD

for your given input..

Try to replace the printf statement with

 printf "$1=\""$1"\",$2=\""$2"\",$3=\""$3"\"\n"

I then get:

$1="AAAAAAA0XXX",$2="KBB BBBBB AD                                                                                             ",$3="BEOGRAD "

Upvotes: 1

anubhava
anubhava

Reputation: 784938

Change this regex:

/^\s*$/

to this:

/^[[:space:]]*$/

As awk/sed regex engine doesn't support \s, \d etc.

Upvotes: 1

Related Questions