-1

I have a list of files (file1, file2, file3...) with an identical string in each one. I'm trying to change the string to read 1, 2, 3, ...

Not sure why my command didn't seem to do anything.

for i in {1..200}; do sed 's/foo/bar$i/g' file$1.txt; done
Cyrus
  • 84,225
  • 14
  • 89
  • 153
John
  • 1
  • 1

2 Answers2

1

To use a variable within a sed string, you'll need to use double quotes:

for i in {1..200}; do sed "s/foo/bar$i/g" file$1.txt; done  # Files will not be modified

This will only print out the result of your sed command.

If you want to make the actual replacement within your file then use the -i operator:

for i in {1..200}; do sed -i "s/foo/bar$i/g" file$1.txt; done  # Files will be modified
Robert Seaman
  • 2,432
  • 15
  • 18
0

What is file$1.txt in a command? Or is this a script, and $1 is the positional parameter? Even then, we're not quite sure what you're trying to do. As others have mentioned, I think you'll need the -i flag to change the files in place, but it would also help to see what's in the files, and what exactly you're trying to do. Perhaps you meant file$i.txt?

But I'm not sure exactly what you're trying to do, so maybe it's best to create backup files:

for i in {1..200}; do sed -i.backup "s/foo/bar$i/g" file$i.txt; done
drewyupdrew
  • 1,549
  • 1
  • 11
  • 16