gdeniz
gdeniz

Reputation: 177

How to pass loop variable as input to cut?

I have a tab separated file:

  c1    1000000
  c2    2000000
  c3    1000000

I would like to loop through each line of that file and save the second column in a variable to then loop through increments of that number and generate a specific new file out of it.

    out=""
    while read i; do
      length=$(echo $i | cut -d$'\t' -f2) #How to use $i here?
      c=$(echo $i | cut -d$'\t' -f1)
      start=1
      end=10000
      for (( i = 0; i < $(expr $length / 500); i++ )); do
        start=$(expr $start + $i \* 500)
        end=$(expr $end + $i \* 500)
        echo $c $start $end >> out
      done
    done <file

Of course, I am always happy to learn about how inefficient my code may be and how I can improve it.

Thanks for your input!

Upvotes: 1

Views: 243

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295443

The problem isn't specific to loops -- it's specific to unquoted echos. As described in BashPitfalls #14, echo $i string-splits and glob-expands the contents of $i before passing them to echo.

Part of string-splitting is that the content are split into words, and the words are passed as separate parameters -- so what it actually runs is echo "c1" "1000000", which doesn't put a tab between the two values, so your cut command can't find a tab to cut on.

The Right Way to fix this is to not use cut at all:

while IFS=$'\t' read -r c length; do

Upvotes: 4

Related Questions