-1

I have a project that contains one file a.txt that contains the text hello, and a folder called b that contains a file c.txt that also contains the text hello. I want to run a bash command that will replace these two instances of hello with goodbye, identical to VSCode's search-and-replace functionality.

I've tried sed -i '.bak' 's/hello/goodbye/g' *, but it gives me the error sed: folder: in-place editing only works for regular files.

How should I approach this? I'm using MacOS.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • The error message is telling you that `*` matches something more than the files you told us about, probably a directory. Voting to close as unreproducible / general computing. – tripleee Sep 22 '22 at 07:13

1 Answers1

0

you can use find to locate the files you need to edit and the --exec param to run your sed command. Something like

find . -name '*.txt' -type f -exec sed -i '.bak' 's/hello/goodbye/g' {} \;
Ian Kenney
  • 6,376
  • 1
  • 25
  • 44
  • When I run that I get `find: --exec: unknown primary or operator` – gkeenley Sep 22 '22 at 01:36
  • Sorry I should mention I'm using a Mac. I've updated the original question. – gkeenley Sep 22 '22 at 01:37
  • should be -exec https://stackoverflow.com/questions/27915657/osx-find-exec-rm-find-exec-unknown-primary-or-operator – Ian Kenney Sep 22 '22 at 01:41
  • It does do the replacements, but it shows the following two outputs: `sed: .: in-place editing only works for regular files` and `sed: ./folder: in-place editing only works for regular files`, and it then creates the .bak backup files for each file. Is there a way to prevent this? – gkeenley Sep 22 '22 at 01:46
  • The idea here is correct, but the code is wrong; it's missing a `-name` predicate before the wildcard `'*.txt'`. Probably add `-type f` before, or instead, depending on what you really need. – tripleee Sep 22 '22 at 07:15