0

I have limited experience with Shell scripting. I was trying to print the comma-separated field with their index number.

I found a similar question here Variables in bash seq replacement ({1..10}) .

IN="abc,def,123"

for i in $(echo "$IN"  | tr "," "\n")
do
  echo $i
done

How can we also print the counter number?

My attempt:

count=1
for i in $(echo "$IN"  | tr "," "\n")
do
  echo $count $i
  count+=1
done

But this does not work.

1 Answers1

4

You need to use the let command to perform arithmetic:

let count+=1

or an arithmetic expression:

((count+=1))

BTW, there's no need to use tr to split the input on commas, you can set IFS.

saveIFS=$IFS
IFS=, 
for i in $IN
do
    echo $i
done
IFS=$saveIFS
Barmar
  • 741,623
  • 53
  • 500
  • 612