0

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

#!bin/bash
oldstring='{alert("bash")}'
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

Giuse Esse
  • 53
  • 1
  • 6
  • 2
    Quote your variable expansions - see [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/a/131767/65304) – steeldriver Feb 03 '21 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 03 '21 at 17:07
  • Running your script with `bash -x yourscript` might help in some cases. Paste it at http://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 03 '21 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 03 '21 at 17:27
  • @guest_7 Ah, yes. I did not see the `-l`. – Kusalananda Feb 04 '21 at 06:38

1 Answers1

2
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'
guest_7
  • 5,698
  • 1
  • 6
  • 13