Kaka
Kaka

Reputation: 151

Bash trouble in for loop variable name

I want to create a shell script in debian that:

  1. creates a directory for each number from 1 to 12 = d1, d2, d3 , ..., d12.
  2. creates the same text file inside every directory
  3. changes a string inside the text file
  4. downloads files using wget

(Create d1; copy links.txt and rename to d1.txt; change every number from 0 to 99 to 1. Then for d2, rename it to d2.txt, change every number to 2 ...the same for the 12).

#!/bin/bash
START=1
END=12
for ((i=START; i<=END; i++))
do
    mkdir d'$i'
    cp /home/user/script/links.txt /home/user/script/d'$i'.txt
    grep -rli '([0-99])' /home/user/script/d'$i'.txt | xargs -i@ sed -i 's/[0-99]/'$i'/g' @
    wget -i /home/user/script/d'$i'/d'$i'.txt
done

What do I need to change to make it work?

Upvotes: 0

Views: 45

Answers (1)

Kurt Stutsman
Kurt Stutsman

Reputation: 4034

Single quotes prevent variable substitution in strings. You should use double quotes instead. Also [0-99] doesn't do what you think. The character classes only match a single character at a time, so you're only looking for characters 0-9 there. I think this should do what you want:

#!/bin/bash
START=1
END=12
for ((i=START; i<=END; i++))
do
    mkdir d"$i"
    sed -r 's/([0-9]|[1-9][0-9])/'$i'/g' /home/user/script/links.txt > "/home/user/script/d$i/d$i.txt"
    wget -i "/home/user/script/d$i/d$i.txt"
done

Upvotes: 1

Related Questions