ywan
ywan

Reputation: 137

AWK prints column depends on header with delimiter comma

I am trying to print columns with the specified column names. But I found when the delimiter is ",", my code cannot split the line. It would print the whole line. Could you help me to figure out this issue?

My input file has 3 columns splited by comma:

AWS_path,path
aws_test1,11111
aws_test2,22222

My code:

input=$1
awk -F "," 'NR==1 {
    for (i=1; i<=NF; i++) {
        f[$i] = i
        print $i
        print f[$i]
    }
} NR>1 { print $(f["AWS_path"]), $(f["path"])}' $input

The result shows the AWS_path and the path. I think it should be:

aws_test1 11111
aws_test2 22222

But indeed it outputs as below, its path column includes the whole line rather than only 2nd column.

aws_test1,11111 aws_test1,11111
aws_test2,22222 aws_test2,22222

I have tried many ways. But I cannot fix it. Could do please help me?

Upvotes: 1

Views: 176

Answers (1)

James Brown
James Brown

Reputation: 37394

Your file has Windows line-endings ie.\r\n instead of just \n, therefore your code has "path" but the file has path\r and no match. Use dos2unix file or similar:

$ awk -f program.awk file    # testing with \r\n endings
AWS_path
1
path
2
aws_test1 aws_test1,11111
aws_test2 aws_test2,22222
$ dos2unix file              # convert to \n
$ awk -f program.awk file    # testing with \n endings
AWS_path
1
path
2
aws_test1 11111
aws_test2 22222

Upvotes: 3

Related Questions