Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...