I'm trying to replace some text in a CMakelists.txt file with the value of a bash variable using sed, but I'm getting an error:
sed: 1: "'s/iPhone": invalid command code ?
sed command:
sed -i "" 's/iPhone Developer/'$PROVPROF'/g' CMakelists.txt
PROVPROF will always have something with this format:
iPhone Developer: Firstname Lastname (Numbers/Letters)
We know that the sed on Mac OS is the POSIX sed, which cannot use many options. On the other hand, GNU sed is very convenient. For example, GNU sed interprets escape sequences like \t , \n , \001 , \x01 , \w , and \b . OSX's sed and POSIX sed only interpret \n (but not in the replacement part of s ).
SED is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits, SED works by making only one pass over the input(s), and is consequently more efficient.
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.
The reason this doesn't work is because sed on linux is different that sed on mac. In order for your commands to work as intended, I recommend installing gnu-sed through homebrew.
You can do this via: brew install gnu-sed --with-default-names
NOTE: --with-default-names
flag will attempt to symlink gnu-sed with your sed, should be what you want but if not, I warned you!
then run hash -r
on bash, or rehash
on zsh.
If it does not work after that, you must manually symlink gnu-sed with sed via:
ln -s /usr/local/bin/gsed $(which sed)
If you have characters in your variable which are the same as the delimiter you used to s
, try using another delimiter instead:
sed -i '' "s|iPhone Developer|$PROVPROF|g" CMakelists.txt
Something more rare:
sed -i '' $'s\xFFiPhone Developer\xFF'"$PROVPROF"$'\xFFg' CMakelists.txt
Also, don't try to store your arguments on a variable. Word splitting would not always work the way you do. This is wrong:
command="sed -i '' 's|iPhone Developer|$PROVPROF|g' CMakelists.txt"
$command
Error message like sed: -e expression #1, char 1: unknown command: `''
would appear. On other sed
s the message may be different.
But you can use an array:
command=(sed -i '' "s|iPhone Developer|$PROVPROF|g" CMakelists.txt)
"${command[@]}"
It's still not commendable though. If you can run it directly, run it directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With