在 awk 或 bash 中递增值

1 bash awk

以下是 .pdb 文件的片段:

ATOM     52  OXT GLU     5     -23.455 -21.595  12.691  0.00  0.00
TER
ATOM      1  N   MET A   1      -9.976  22.279  65.378  1.00 37.35           N
ATOM      2  H   MET A   1      -9.180  21.915  65.882  1.00 37.35           H
Run Code Online (Sandbox Code Playgroud)

我想在 bash 或 awk 中编写一个脚本,它将 .pdb 文件中第一个“TER”之前的行中第二列的值增加 +1,并且这些值将直接保存到行中的第二列在“TER”之后。具体来说,我正在寻找这样的东西:

ATOM 52 OXT GLU 5 -23.455 -21.595 12.691 0.00 0.00
TER
ATOM 53 N MET A 1 -9.976 22.279 65.378 1.00 37.35 N
ATOM 54 H MET A 1 -9.180 21.915 65.882 1.00 37.35 H
Run Code Online (Sandbox Code Playgroud)

我尝试过这样的事情:

#!/bin/bash

# Get the value of the second column in the last line before "TER"
last_col2=$(grep -v "TER" model.pdb | awk '{if($2>max){max=$2}}END{print max}')
new_col2=$((last_col2+1))

# Loop through the lines of the input file
while read line; do
  if [[ "$line" == "TER" ]]; then
    # Skip "TER" line, but print it to the output file
    echo "$line" >> model_new.pdb
  else
    # Increment the second and fifth columns for lines after "TER"
    # and print the updated line to the output file
    col2=$(echo "$line" | cut -c 7-11 | tr -d '[:space:]')
    if [[ "$col2" -eq 1 ]]; then
      new_line=$(echo "$line" | sed "s/$col2/$new_col2/")
      echo "$new_line" >> model_new.pdb
    else
      echo "$line" >> model_new.pdb
    fi
  fi
done < model.pdb
Run Code Online (Sandbox Code Playgroud)

但这不起作用。你帮我吗?

Kam*_*Cuk 5

会将 .pdb 文件中第一个“TER”之前的行中第二列的值增加 +1,并且这些值将直接保存到“TER”之后的行中的第二列

awk '
  seenTer{ $2 = ++beforeTerValue }
  /TER/{ seenTer=1 }
  !seenTer{ beforeTerValue = $2 }
  1
' inputfile > outputfile
Run Code Online (Sandbox Code Playgroud)