find a string and add string

2019-09-19 20:54发布

问题:

I have multiple file...it looks like:

ATOM   1244  O   VAL   160       7.381  11.465  -2.646   1.000  60.790   0.000
ATOM   1245  CB  VAL   160       5.766  13.870  -0.914   1.000  57.640   0.000
ATOM   1246  CG1 VAL   160       7.232  14.074  -0.568   1.000  57.530   0.000
ATOM   1247  CG2 VAL   160       5.065  15.213  -1.089   1.000  58.420   0.000
ATOM   1248  N   VAL     1     -14.324 -25.299   8.568   1.000  77.840   0.000
ATOM   1249  CA  VAL     1     -14.315 -23.826   8.346   1.000  78.450   0.000
ATOM   1250  C   VAL     1     -15.181 -23.169   9.426   1.000  76.690   0.000

Now i have to add "TER" after line:

ATOM   1247  CG2 VAL   160       5.065  15.213  -1.089   1.000  58.420   0.000

This line is same in all the files. So its like i should find this line in all the files and then add "TER" after this line..

I think line can be searched through grep or sed..but how can string be added in the next line? Iam not clear about this code at all..will some one help plz...

回答1:

Try running this on shell:

/usr/bin/perl -p -i -e "s/(ATOM\s+1247\s+CG2\s+VAL\s+160\s+5.065\s+15.213\s+-1.089\s+1.000\s+58.420\s+0.000)/\$1\nTER/g" my.allfiles

"-p" causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed:

  1. LINE:
  2. while (<>) {
  3. ... # your program goes here
  4. } continue {
  5. print or die "-p destination: $!\n";
  6. }

If a file named by an argument cannot be opened for some reason, Perl warns you about it, and moves on to the next file. Note that the lines are printed automatically. An error occurring during printing is treated as fatal. To suppress printing use the -n switch. A -p overrides a -n switch.

http://perldoc.perl.org/perlrun.html



回答2:

Sed, awk or perl are the tools to use here.

sed has a short man page. Read it and you will learn all kinds of tricks.

Look in there for pattern matching, then I think there is a command to add text to the end of the line.



回答3:

find root-path-to-search -type f -execdir sed -r \ 
's/^(\s*ATOM\s+1247\s+CG2\s+VAL\s+160\s+5\.065\s+15\.213\s+-1\.089\s+1\.000\s+58\.420\s+0\.000\s*)$/\1\nTER\n/' {} \+


标签: linux string add