Vikas
Vikas

Reputation: 73

Escape character for replacement character in unix

What's the escape character for & (to include the match in the replacement)?

I need to replace cat in file with &quo;cat&quo;

cat file | sed -e 's\cat\&quo;cat&quo;\'

Upvotes: 1

Views: 265

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52281

\ is not an optimal choice for the substitution delimiter – / is often used, and much better suited in this case because \ is used for escaping:

sed 's/cat/\&quo;cat\&quo;/' file

Notice that you don't have to use cat to pipe to sed; just give the input file as an argument.

& has to be escaped to get a literal &; otherwise, it stands for the whole matched portion of the pattern space (see the manual):

$ sed 's/XXX/~&~/' <<< 'aaaXXXaaa'
aaa~XXX~aaa
$ sed 's/XXX/~\&~/' <<< 'aaaXXXaaa'
aaa~&~aaa

Upvotes: 3

Iresha Rubasinghe
Iresha Rubasinghe

Reputation: 953

Characters that need escaping are different in Bourne or POSIX shell than Bash. Generally (very) Bash is a superset of those shells, so anything you escape in shell should be escaped in Bash.

A nice general rule would be "if in doubt, escape it". But escaping some characters gives them a special meaning, like \n. These are listed in the man bash pages under Quoting and echo.

Other than that, escape any character that is not alphanumeric, it is safer. I don't know of a single definitive list.

The man pages list them all somewhere, but not in one place. Learn the language, that is the way to be sure.

One that has caught me out is !. This is a special character (history expansion) in Bash (and csh) but not in Korn shell. Even echo "Hello world!" gives problems. Using single-quotes, as usual, removes the special meaning.

Upvotes: 0

Related Questions