Deano
Deano

Reputation: 12200

replacing $ and # from file

I have file with comments like this:

\$max_servers = 2;    

\#\## BLOCKED ANYWHERE 

I'm trying to

I wonder how I can go about doing that via sed or awk

What I have tried so far without much success using vi or vim

%s/^\//gc

%s/^#/\\/###/gc 

Thank you

Upvotes: 2

Views: 67

Answers (5)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's|^\\\([$#]\)\\\{0,1\}|\1|' YourFile

work for your sample bu will also remove the 2 \ in \$\ ...,

Upvotes: 1

sovemp
sovemp

Reputation: 1413

You escape special characters with the backslash. So for example, to replace everything with \$, you would do %s/\\\$/$/g

Upvotes: 1

David W.
David W.

Reputation: 107060

In order to replace a backslash, you have to double it up, so it can quote itself much the way other special characters must be quoted. You can use sed instead of vim to help automate the process a bit:

$ sed -e 's/^\\\$/$/' -e 's/^\\#\\##/###/' $file > $new_file

Note that you have to put a backslash in front of dollar signs since they are used to mark an end of line in regular expressions. That's why I have \\\$ in my first expression. One backslash to quote the backslash and another backslash to quote the dollar sign.

By the way, these same sed expressions will also work inside Vim depending upon your Vim settings.

Upvotes: 1

nimrodm
nimrodm

Reputation: 23829

Another option to replace all [#$] in one pass is to use the following regular expression. The following is VI syntax:

:%s/\\\([$#]\)/\1/g

Replace the characters in the brackets [] with whatever you need if its more than just # and $.

The first \\ is a backslash - escaped since its inside a regular expression The expression between the \( and \) is saved and later used in the replacement as \1.

Upvotes: 3

Raul Andres
Raul Andres

Reputation: 3806

Escaping backslash will work

 #echo "\#\##"| sed "s/\\\\#\\\\##/###/g"
 ###
 # echo "\\$"| sed "s/\\\\\\$/$/g"
 $

Upvotes: 1

Related Questions