awkparameters

passing "-e" as a parameter to awk is having unexpected results


I have short Bash script that will not pass "-e " to Awk:

str="Morgenstern"
ex = "-e "
for i in {1..11}
do
    echo $(echo $str| awk -v vv="$i" -v xx="$ex" 'print xx substr ($0,vv,1)}')
done
 

the results should be:

-e M
-e o
-e r

etc...

the actual result is

M
o
r

If I change ex to "-b " then I get the expected result (-b M, -b o, etc.)

I also tried hard coding "-e " in the Awk statement with the same bad result.

How do I get Awk to accept "-e " as a parameter or as a literal?


Solution

  • The issue is the redundant echo, which through $(…) is being passed two arguments and one it recognizes as an option:

    echo -e M
    

    Remove the redundant echo, and avoid the same problem with the other one by using printf.

    str="Morgenstern"
    ex="-e "
    for i in {1..11}
    do
        printf %s "$str" | awk -v vv="$i" -v xx="$ex" '{ print xx substr($0, vv, 1) }'
    done
    

    Also, awk has for loops.

    str="Morgenstern"
    ex="-e "
    printf %s "$str" | awk -v xx="$ex" '{
        for (i = 1; i <= length($0); i++) {
            print xx substr($0, i, 1)
        }
    }'