That script looks absolutely fine to me. That should just work.
Are you sure you don't have any weird characters between the end of line 5 and the start of line 6?
I've just tested your code in a sub-directory of my linux.org directory, where I put any programs/scripts that I've worked on for people in threads here at linux.org. I add a directory for each user - that way I can associate a script with the user who asked a particular programming/scripting question.
To test your script - this is the actual code I used.
for file in ~/Projects/linux.org/BenTom07/*
if [[ "$file" =~ \.txt$ ]]
sed -i 's/old text/new text/g' "$file"
I created three .txt files in the BenTom07/ directory which were just filled with lines containing "old text". I ran your script and as expected - all three of the .txt files were populated with "new text" instead.
So I have no idea why you're getting that error. Your code works properly for me!
The only things I changed in the script were the
, to ensure it used a valid path that exists on my system. Also in the
invocation, I have put double quotes around
to ensure that the filename is properly quoted. That will avoid problems if any of the
files contain names with spaces or other special characters. Spaces and special characters in file-names either need to be double quoted, or escaped. So in a script, it makes sense to use double-quotes when de-referencing strings from variables. Especially if they contain file-names. But that change will have had nothing to do with the error you were getting.
So I'm mystified. The code you've posted is absolutely fine. I dont' know how/why you're getting that error.
The only thing I can think of is, perhaps your script has some kind of funky character somewhere between line 5 and line 6? Or between line 6 and line 7.
But everything you've posted is OK!