1

I have a file containing hundreds of values that start with $.

$ cat /tmp/file

$one $t $three
$one $t $three $t $three

I'm trying to use sed to replace only the values that start with $t.

$ sed "s/\$t/foo/g" /tmp/file

$one foo foohree
$one foo foohree foo foohree

But the above command replaces the $three values as well. How can I prevent this?

1
  • To avoid future confusion, I recommend that you use single quotes (') to quote regular expressions on the command line. Typical shells turn "\$" (with double quotes) into the literal $ which is a meta-character for the end-of-string in sed regular expressions. It just so happens that sed interprets it as a literal $ if it occurs at the beginning of a regular expression literal. However, if you write '\$', it becomes \$ and sed will know that you want to match the literal $ character (and not end-of-string) regardless of its position in the regular expression. – David Foerster Aug 8 '20 at 7:23
3

try:

sed "s/\$t\>/foo/g" /tmp/file

\> is a regular expression pattern match for the end of the word.

1
  • thanks so much. – user427367 Aug 8 '20 at 2:51
0

Tried with below sed and awk command

 awk '{for(i=1;i<=NF;i++){if($i =="$t"){gsub(/\$t/,"foo",$i)}}}1'  filename

sed command

sed "s/\$t /foo /g" filename

output

$one foo $three
$one foo $three foo $thre

e

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.