2

So the idea is to replace matched pattern nas_... with nas_$SCL using $SCL variable in a file, but excluding 2 exact matches nas_mba && nas_tvr, which should not be replaced

So far I've got code excluding both matches, but also interfering with other unwanted matches

sed -i "s/nas_[^mt][^bv][^ar]/nas_$SCL/gI" filename.xml

How can I exclude only those 2 exact matches?

Update: So far I've found next solution

sed -i "/(nas_mba|nas_tvr)/! s/nas_.../nas_$SCL/"

but it skips a whole line if it has a match

2 Answers 2

2

Here is how I would do it:

sed -E '/(nas_mba|nas_tvr)/! s/nas_.../nas_bar/'

Example:

echo "nas_mba
nas_tvr
nas_foo" | sed -E '/(nas_mba|nas_tvr)/! s/nas_.../nas_bar/'
nas_mba
nas_tvr
nas_bar

Only nas_foo in the original text is replaced, while both nas_mba and nas_tvr are left untouched.

Another example with more lines:

echo "nas_hat
> nas_mba
> nas_foo
> nas_hat
> nat_tvr
> nas_cat
> nas_dog" | sed -E '/(nas_mba|nas_tvr)/! s/nas_.../nas_bar/'
nas_bar
nas_mba
nas_bar
nas_bar
nat_tvr
nas_bar
nas_bar

If you want to change in place, just add the -i option (if you use GNU sed you don't need -i "" simply -i would suffice):

sed -E -i "" '/(nas_mba|nas_tvr)/! s/nas_.../nas_bar/' nas.txt 
cat nas.txt 
nas_bar
nas_mba
nas_bar
nas_bar
nat_tvr
nas_bar
nas_bar

Tested under Mac OS X 10.11.6 and BSD sed.

4
  • yes, this is a good example, but this should be replace lines in a file, thus needing -i flag Commented Feb 3, 2017 at 8:15
  • 1
    Well, simply add the -i flag. See my edit. Commented Feb 3, 2017 at 8:18
  • cheers, works as intended Commented Feb 3, 2017 at 8:23
  • @MaxShepelev You're welcome! Commented Feb 3, 2017 at 8:24
2

If perl is an option, you could use lookahead:

export SCL
perl -pe 's/nas_(?!mba|tvr)\w*/nas_$ENV{SCL}/g' file

(note that this assumes the sequences you do want to match consist of word characters - it can be modified if that's not the case).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.