Lord OfTheRing
Lord OfTheRing

Reputation: 1309

Shell Script read CSV file (Skip Header)

I have below SH script which reads test.csv file but it is not printing command what I am expecting. Please help

read header
while IFS="," read -r user role
do
    echo "btp assign security_role-collection $role --to-user $user"
    
done
} < test.csv

test.csv file records as below

user,role
[email protected],testrole1
[email protected],testrole2

Results what I am getting is:

 --to-user [email protected] testrole1
 --to-user [email protected] testrole2
btp assign security_role-collection  --to-user

but I am expecting below results instead. What am I doing wrong ?

btp assign security_role-collection  testrole1 --to-user [email protected]
btp assign security_role-collection  testrole2 --to-user [email protected]

Upvotes: 0

Views: 1233

Answers (1)

glenn jackman
glenn jackman

Reputation: 247210

When you read this line [email protected],testrole1 and the line has \r\n line endings, the value of $role is testrole1\r

The string you create looks like

btp assign security_role-collection testrole1\r --to-user [email protected]
.............................................^^

And when you print it, the carriage return moves the cursor to column 1.

You want

{
read header
while IFS="," read -r user role
do
    echo "btp assign security_role-collection ${role%$'\r'} --to-user $user"
    # ........................................^^^^^^^^^^^^^
done
} < test.csv

or

{
read header
while IFS="," read -r user role
do
    echo "btp assign security_role-collection $role --to-user $user"
done
} < <(sed 's/\r$//' test.csv)
# ..^^^^^^^^^^^^^^^^^^^^^^^^^

Upvotes: 1

Related Questions