Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Awk or Bash, Replacing string from specific column and line number to foreward

I want to substituted capital letter B with C in column 5 and from line 6 to the end of the file, need to keep the spaces as it is from my original input file as it is.

ATOM   1939  HG2 PRO A 125      35.681  32.906  38.437  1.00 43.59           H  
ATOM   1940  HG3 PRO A 125      34.593  33.765  37.652  1.00 41.79           H  
ATOM   1941  HD2 PRO A 125      37.364  34.075  37.624  1.00 43.38           H  
ATOM   1942  HD3 PRO A 125      36.333  34.312  36.415  1.00 41.29           H  
TER   
ATOM   1944  N   MET B  11      16.583  29.975  -4.306  1.00 51.32           N  
ATOM   1945  CA  MET B  11      15.542  30.263  -3.327  1.00 39.92           C  
ATOM   1946  C   MET B  11      16.146  30.366  -1.933  1.00 32.50           C  

I have read:

  1. https://unix.stackexchange.com/questions/486840/replace-a-string-with-sed-from-specific-lines
  2. https://unix.stackexchange.com/questions/70878/replacing-string-based-on-line-number
  3. Sed replace pattern with line number

and my attempt is: awk 'NR == 6 && $ == 5, { sub(" B ", " C ") }'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This simple awk should help you in same. Written and tested in GNU awk.

awk '
FNR>=6 && match($0,/^(\S+[[:space:]]+)(\S+[[:space:]]+)(\S+[[:space:]]+)(\S+[[:space:]]+)(\S+)(.*)$/,arr) && arr[5]=="B"{
  $0=arr[1] arr[2] arr[3] arr[4] "C" arr[6]
}
1
'  Input_file

Using match function here to keep your spaces as it is even after substitution.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading