简体   繁体   中英

Replace string in bash script (MacOS)

I have the following code generated in a Makefile:

    ${SED} -i '' -e "s|(DESTDIR)|${DESTDIR}|g" $(pcfiles)
#   ${SED} -i "s|(DESTDIR)|${DESTDIR}|g" $(pcfiles)

Which I want to replace with

#   ${SED} -i '' -e "s|(DESTDIR)|${DESTDIR}|g" $(pcfiles)
    ${SED} -i "s|(DESTDIR)|${DESTDIR}|g" $(pcfiles)

So it's simply a matter of commenting out one line,and replacing with the other.

But due to the single quotes and double quotes I can't achieve it.

If some regex expert is willing to take 1-2 minutes to help me out that will be great.

I'm pulling my hairs out here.

Thanks

# Comment out 1st line.
sed -E 's`([[:space:]]*\$\{SED\} -i '"''"' -e "s\|\(DESTDIR\)\|\$\{DESTDIR\}\|g" \$\(pcfiles\))`#\1`' Makefile
# Uncomment 2nd line.
sed -E 's`#([[:space:]]+\$\{SED\} -i "s\|\(DESTDIR\)\|\$\{DESTDIR\}\|g" \$\(pcfiles\))`\1`' Makefile 

The sed commands are in single-quoted strings, which are generally easier to use (you needn't worry about the shell expanding your string).

The tricky aspect of the first command is that single quotes cannot be included in a single-quoted string (even escaping is not an option), so the command is simply broken into two single-quoted strings with "''" - amounting to '' - spliced in.

The other tricky aspect is to get the escaping of all special regex chars. right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM