2

I want to insert a counter into a text file using sed. For example, the file has the following content:

please.add.number.00

Here is the script I'm using:

for i in $(seq 0 10)
do
sed -i 's/please.add.number.00/please.add.number.$i/' filename.txt
done

But the value ($i) in the file doesn't change. I want to substitute the value of $i in this line of filename.txt. I would appreciate any help to fix this issue!

Stephen P
  • 14,422
  • 2
  • 43
  • 67
SBC
  • 125
  • 2
  • 11
  • 1
    Variables don't expand in single quotes. Use double quotes. – Etan Reisner Nov 24 '15 at 19:23
  • Are you sure you want `seq 10 10` ? – Petr Skocik Nov 24 '15 at 19:34
  • `$(seq 10 10)` just produces `10` so there's no looping. If there *was* a loop (say 'seq 10 20'), this would replace all `...number.00` with `...number.10` and no more replacements would take place, because there would be no more '...number.00' left after doing the first replacement. Also note that the dots in `please.add.number.00` are *wildcards* while those in `please.add.number.$i` are literal *periods.* – Stephen P Nov 24 '15 at 19:35
  • sorry there was a typo in the for loop; it should be for i in $(seq 0 10) – SBC Nov 24 '15 at 19:37
  • 1
    the goal is to change the value from 1 to 50 in this line ..i thought sed would do it..and double quote in sed .."...." did not work. – SBC Nov 24 '15 at 19:40

1 Answers1

1

As mentioned in comments, there is a difference between these two lines:

echo '$HOME'
echo "$HOME"

Single quotes will result in $HOME, double quotes will tell you your home directory.

Based on edits to your question, it looks like your actual problem is a case of misunderstanding how sed works. The substitute command takes two parameters: a search pattern and a replacement. If the search pattern (please.add.number.00) never changes, then it will only ever be matched the first time it is run.

Community
  • 1
  • 1
miken32
  • 42,008
  • 16
  • 111
  • 154