1

In sed, how can I do pattern replacement when a line doesn't contain certain pattern?
I know how to do it in vi or vim.
For example, to replace 'rabbit' to 'hare' when the line does not contain 'animal', I can do

:g!/animal/s/rabbit/hare/g

I want to do the same thing for hundreds of files under a directory using foreach, find and sed. When the line does not contain '= (Dtype)', I want to replace 'Dtype val1 = expression;' to 'Dtype val1 = (Dtype)(expression);'. But excluding cases like 'Dtype *pval = expression;'. That is, I want to put (Dtype) casting for non-pointer assignments. I tried

>foreach i (`find . -name \*.c`)
? sed -e 'g!/ = (Dtype)/s/Dtype \([a-z].*\) = \(.*\);/Dtype \1 = (Dtype)(\2);/g' $i >! tmp
? mv tmp $i
? end

But this 'g!/pattern/s/patter1/pattern2/g' doesn't work in sed. What's the correct command?

Chan Kim
  • 5,177
  • 12
  • 57
  • 112
  • @Sundeep Hi, your reference is in the Documentation. How can I search for it? separately in the Documentation section? – Chan Kim Jul 25 '17 at 06:18
  • 1
    Possible duplicate of [How to globally replace strings in lines NOT starting with a certain pattern](https://stackoverflow.com/questions/4953738/how-to-globally-replace-strings-in-lines-not-starting-with-a-certain-pattern) – Sundeep Jul 25 '17 at 06:23
  • dunno about search leading to that documentation reference, but the first link I got when search online with exact question title solves your question... – Sundeep Jul 25 '17 at 06:24

1 Answers1

2

This might work for you (GNU sed):

sed '/animal/!s/rabbit/hare/g' file

Search for animal and if it is not found replace rabbit by hare globally.

potong
  • 55,640
  • 6
  • 51
  • 83