A. Gupta
A. Gupta

Reputation: 87

How to replace a text string with dollar sign $ in Linux?

I am trying to replace a text '../../Something' with '$Something' in all .txt files in current directory.Let me know where I am going wrong?

find . -name "*.txt" | xargs sed -i "s/..\/..\/Something/\'\$Something'/g"

Error - Variable name must contain alphanumeric character

I also tried with but doesn't work-

find . -name "*.txt" | xargs sed -i "s/..\/..\/Something/\\$Something/g"

Any suggestions for correct command?

Upvotes: 0

Views: 2162

Answers (3)

Diksha P
Diksha P

Reputation: 31

You can try removing the extra backslash given in the second command.

find . -name "*.txt" | xargs sed -i 's/../../Something/\$Something/g'

Upvotes: 1

Hargo
Hargo

Reputation: 1266

You're shell is treating the $ as the start of a variable.

There are two ways you can make it work:

  1. Use single quotes, which tells the shell to not perform any variable interpolation (among other things):

    find . -name "*.txt" | xargs sed -i 's/..\/..\/Something/\$Something/g'

  2. Escape the $ from the shell and sed. This requires 3 backslashes (the first one escapes the second backslash, the second escapes the dollar sign once the tring reaches sed, and the third escapes the dollar sign in the shell so it doesn't get treated as a variable):

    find . -name "*.txt" | xargs sed -i s/..\\/..\\/Something/\\\$Something/g

Upvotes: 1

nu1silva
nu1silva

Reputation: 149

Tested the following and it worked for me. Let me know if this works

find . -name "*.txt" | xargs sed -i "s,../../Something,$\Something,g"

Upvotes: 0

Related Questions