0

I am accessing a remot HPC through iterm2 in my MacBook Air. Sometime above command works perfectly fine but sometime it gives the error. Can anybody please help me to find out my mistak in it. I am following below format:

sed -i 's/search_string/replace_string/' filename

sed -i 's/ashu/vishu/' test.txt

muru
  • 72,889

1 Answers1

4

The non-standard -i option of sed on macOS takes a mandatory argument, the filename suffix to use to create backup files.

On macOS, if you want to use in-place editing with no backup file, use an empty backup suffix:

sed -i '' 's/ashu/vishu/' test.txt

However, this would do the wrong thing with GNU sed, and it's not clear from your question which sed implementation you're ending up using.

To portably do an in-place edit, use the following:

cp test.txt test.txt.tmp &&
sed 's/ashu/vishu/' <test.txt.tmp >test.txt &&
rm -f test.txt.tmp

That is, copy the original file to a temporary name. Then apply the sed operation on the temporary named file, redirecting the output to the original file. Then delete the temporary name.

Using && between the operations as I've done above ensures that one step is not taken unless the previous step has finished successfully.

See also:

Kusalananda
  • 333,661