0

I have a file that looks like this:

C        0.749421709   0.227878968   1.429202011   0.000039192  
C        1.632642695  -0.091443576   2.542631832  -0.000184939  
N        0.043615933   0.482209037   0.540453037   0.000123677   
H        2.515045687   0.527073165   2.500388888  -0.001989853   
H        1.941072900  -1.159598231   2.494001492   0.001039872   
H        1.143298831   0.111732200   3.499873978   0.001236466     

which is a pattern that repeats several times across the entire file. I need to change only the "C" right above the "N" for "Cn" in the entire file. I tried to use sed but none of the variations seem to work. I am able to find the pattern and add stuff either above or below, but I am not able to replace the "C" for "Cn".

1

Try by reverse listing the original file

tac file | awk '/^N/ {NT = 1} /^C/ && NT {sub (/^C /, "Cn"); NT = 0} 1' | tac
| improve this answer | |
  • it works very nicely and fast. Thank you – Pablor Jan 7 at 17:40
2

One solution :

tac file |
    awk '{if ($1=="C" && l=="N") $1="Cn"} {l=$1} 1' |
    tac |
    column -t

Output

C   0.749421709  0.227878968   1.429202011  0.000039192
Cn  1.632642695  -0.091443576  2.542631832  -0.000184939
N   0.043615933  0.482209037   0.540453037  0.000123677
H   2.515045687  0.527073165   2.500388888  -0.001989853
H   1.941072900  -1.159598231  2.494001492  0.001039872
H   1.143298831  0.111732200   3.499873978  0.001236466
| improve this answer | |
  • it works thank you – Pablor Jan 7 at 17:39
0

You could do something like this in sed I think:

sed -e '$!N;/^C.*\nN/s/^C/Cn/' -e 'P;D' file

This maintains a 2-line buffer in pattern space and replaces a leading C if there is a N at the start of the second line.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.