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
824 views
in Technique[技术] by (71.8m points)

perl - How to replace a comment line which start with specific characters

I have a fortran code with global comments, which start with a double exclamation mark (i.e., !!) and personal comments, which start with a single exclamation mark (i.e., !), and I just want to hide my personal comment lines (or substitute the line with another line, e.g., '! jw'). For example, the original code looks like this:

!! This is a global comment  
Code..
Code..

! This is a personal comment 
code... ! This is a personal comment

!! This is a global comment
code...

Then, I want to update the original code as:

!! This is a global comment  
Code..
Code..

! jw
code... ! jw

!! This is a global comment
code...

I have tried to use "sed" and "awk", but I failed. So, would someone can help me? I prefer to use "sed" instead "awk" by the way.

question from:https://stackoverflow.com/questions/65922689/how-to-replace-a-comment-line-which-start-with-specific-characters

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

1 Answer

0 votes
by (71.8m points)
  •  sed '/!!/!s/!.*/! jw/' file
    
    • /!!/! If the line does not contain !!, then
    • s/!.*/! jw/ substitute all following a exclamation mark with ! jw.
  • awk 'BEGIN{FS=OFS="!"}$2{$2=" jw"}1' file
    
    • BEGIN{FS=OFS="!"} Set the field separators to !.
    • $2{$2=" jw"} If the 2nd field is not empty, substitute it by jw.
    • 1 Print the line.

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

...