Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

bash - How to make sed avoid replacement after specific symbol

I am writing a script for formatting a Fortran source code. Simple formatting, like having all keywords in capitals or in small letters, etc. Here is the main command

sed -i -e "/^!/! s/$smalls/$cap /gI" $filein

It replaces every keyword $small (followed by a space) by a keyword $caps. And the replacement happens only if the line does not start with the "!". It does what it should. Question:

How to avoid replacement if "!" is encountered in the middle of a line. Or more generally, how to replace patterns everywhere, but not after a specific symbol, which can be either in the beginning of the line or somewhere else.

Example:

Program test  ! It should not change the next program to caps
! Hi, is anything changing here? like program ?
This line does not have any key words
This line has Program and not exclamation mark. 

"program" is a keyword. After running the script the result is:

PROGRAM test  ! It should not change the next PROGRAM to caps
! Hi, is anything changed here? like program ?
This line does not have any key words
This line has PROGRAM and not exclamation mark.

I want:

PROGRAM test  ! It should not change the next program to caps
! Hi, is anything changed here? like program ?
This line does not have any key words
This line has PROGRAM and not exclamation mark.

So far, I've failed to find a nice solution, which does the trick, hopefully with the sed command.

question from:https://stackoverflow.com/questions/65904819/how-to-make-sed-avoid-replacement-after-specific-symbol

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The typicall way in sed is to:

  • split the string into two parts - save one part in hold space.
  • do operations on pattern space
  • get hold space and shuffle for output.

Would be something along:

sed '/!/!b;/[^!]/{b};h;s/.*!//;x;s/!.*//;s/program/PROGRAM/gI;G;s/
/!/'
  • /!/!b; - if the line has no !, then print it and start over.
  • h;s/.*!//;x;s/!.*// - put part after ! in hold space, part before ! in pattern space
  • s/program/PROGRAM/gI; - do the substitution on part of the string
  • G;s/ /!/ - grab the part from hold space and shuffle output - it's easy here.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...