0

I am thinking to replace a string in linux, the idea is to find all files having abc as string and replace with xyz inside a directory and all sub-directories.

Can you suggest how can I do this with Linux shell scripting

4
  • find + sed. What have you attempted, why does it not work?
    – knittl
    Commented Oct 11, 2022 at 7:03
  • i have tried grep -l -r with sed But the changes seems to be improper When i use sed finding a error sed: couldn't edit : not a regular file
    – User_01
    Commented Oct 11, 2022 at 7:14
  • Please edit the question to include all details.
    – knittl
    Commented Oct 11, 2022 at 7:16
  • See unix.stackexchange.com/questions/112023/…
    – Sundeep
    Commented Oct 11, 2022 at 7:54

1 Answer 1

2

You can use find and sed, since sed will only affect files which have this string. If a file does not have the string, there's no disadvantage of running the replace anyway:

find -type f -exec sed -i 's/abc/xyz/g' {} +
  • -type f only find files (exclude directories)
  • -exec for each file found execute …
  • sed -i edit files in-place
  • s/abc/xyz/g replace all occurrences of "abc" with "xyz" in all lines
  • {} + invoke the "exec" command with multiple file names at once, instead of once per file
2
  • shouldn't the sed command be 's/abc/xyz/g'?
    – MAZ
    Commented Oct 21, 2023 at 10:56
  • 1
    @AMS yes, thank you! The explanation was correct, but the full code block was incorrect. Thanks for noticing!
    – knittl
    Commented Oct 21, 2023 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.