简体   繁体   中英

Find and replace with sed command for Tcl command args symbol

I am trying to replace a string in a file which has tcl command delimiters '[]' using sed

Example:

string [$HelloWorld] has to be replace by $HelloWord . Please note that it doesn't have brackets and to be modified file is TCL file. How would I do that using sed command?

I tried this:

sed -i 's@[$HelloWorld]@$HelloWorld@g' <file_path>

You need to escape [ and ] because they are interpreted as characters classes in regexp and not literal square brackets:

$ sed 's/\[$HelloWorld\]/$HelloWorld/g' file
string $HelloWord

You can make use of capture groups here:

$ sed 's/\[\($HelloWorld\)\]/\1/g' file
string $HelloWord

Use sed 's/[][]//g' if you want to remove all square brackets from a file:

# First check changes are correct
$ sed 's/[][]//g' file
string $HelloWorld

# Store the change back to the file 
$ sed -i 's/[][]//g' file

# Store changes back to the file and create back up of the original 
$ sed -i.bak 's/[][]//g' file

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