Ubuntu – Retain white spaces in fields when using awk

awkbashcommand linetext processing

I am using nawk on a pipe delimited file to print fields as index and key where some of the fields contain white space, when there is no white space everything works normal, but in case of white spaces somehow awk treats it as field separator and prints this o/p to new line. See my input below :

Input:

a|b|c d e|1|2|3
a|b c|d|1|2|2 3

Output:

Index=a|b|c 
Key=1|2|3
Index=d
Key=<null>
Index=e
Key=<null>
Index=a|b
Key=1|2|2
Index=c|d
Key=3

Expected Output:

Index=a|b|c d e
Key=1|2|3
Index=a|b c|d
Key=1|2|2 3

In short for two record 2 Index and 2 keys and keep the basic white spaces as it is.

I have to use below set of code for working on each line because there are too many fields and having huge data

    index=`echo "$line" | nawk -F '|' '
    function select_from(from,to,delim)
    {
            if (to < from) { return; };
            for (i=from;i<=to;i++)
            {
                            if (NF < i) { break;};
                            if (i < to)
                            {
                                    printf("%s%s",i,delim);
                            } else {
                                    printf("%s",i);
                            };
            };
    }
    {select_from(11,48,"|");};'`

response are correct when using some special character instead of space, but that is not correct on input data. so want to know if I can preserve space in this process.

Best Answer

Using awk

from=1; to=3; delimiter="|"; awk -F"$delimiter" -v from="$from" -v to="$to" '!/^[[:blank:]]*$/ {printf "Index="; for(i=from; i<=to; i++) {printf $i; if(i<to) {printf "|"};} printf "\n"; printf "Key="; for(i=to+1; i<=NF; i++) {printf $i; if(i<NF) {printf "|"};} printf "\n"}' foo

More readable

from=1; to=3; delimiter="|";
awk -F"$delimiter" -v from="$from" -v to="$to" '!/^[[:blank:]]*$/ {
    printf "Index=";
    for(i=from; i<=to; i++) {
        printf $i;
        if(i<to) {
            printf "|"
        };
    }
    printf "\n";
    printf "Key=";
    for(i=to+1; i<=NF; i++) {
        printf $i;
        if(i<NF) {
            printf "|"
        };
    }
    printf "\n"
}' foo

Example

$ cat foo
a|b|c d e|1|2|3
a|b c|d|1|2|2 3

$ from=1; to=3; delimiter="|"; awk -F"$delimiter" -v from="$from" -v to="$to" '!/^[[:blank:]]*$/ {printf "Index="; for(i=from; i<=to; i++) {printf $i; if(i<to) {printf "|"};} printf "\n"; printf "Key="; for(i=to+1; i<=NF; i++) {printf $i; if(i<NF) {printf "|"};} printf "\n"}' foo
Index=a|b|c d e
Key=1|2|3
Index=a|b c|d
Key=1|2|2 3