Hello I need to replace a string but i receive error using string 'return false;'

newstring='{return false;}'
grep -rl $oldstring /home/commons.bundle.js | xargs sed -i s/$oldstring/$newstring/g

error: sh deleteBoo.sh sed: espressione -e #1, carattere 25: comando `s' non terminato

  • 2
    Quote your variable expansions - see Why does my shell script choke on whitespace or other special characters? Feb 3, 2021 at 16:58
  • 1
    As two side notes, there's no need to recursively grep against one file; additionally, there's no need to grep for the string, since sed will only replace strings that it matched.
    – Jeff Schaller
    Feb 3, 2021 at 17:07
  • Running your script with bash -x yourscript might help in some cases. Paste it at shellcheck.net to check for errors with automatic suggestions how to fix some problems. (Unfortunately shellcheck doesn't suggest to quote all variables.)
    – Bodo
    Feb 3, 2021 at 17:24
  • Apart from what others have said, running sed from xargs with the output of grep will likely not do what you want as the lines matching the expression given to grep would be used as arguments, not input data, with sed.
    – Kusalananda
    Feb 3, 2021 at 17:27
  • @guest_7 Ah, yes. I did not see the -l.
    – Kusalananda
    Feb 4, 2021 at 6:38

1 Answer 1

grep -rlZF -- "$oldstring" /home/commons.bundle.js |
xargs -r0 sed -i "s/$oldstring/$newstring/g" -- 

The following minor changes should make it work:

  • grep should use -F so that the strings passed are not evaluated by grep as regexes.
  • Another grep option to use is -Z which will pass filenames onto xargs using the null delimiter.
  • At the receiving end, xargs with -0 will unpack safely the filenames now. Nulls cannot occur in filenames by `law'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .