sed/awk/perl: find a regex, copy 5 columns of this line and paste to it at the beginning of the next lines

↘锁芯ラ 提交于 2020-01-05 06:33:26

问题


I have following lines:

057         -   -   No    adod3 stptazlqn    10    753
tlm    10    027        
stp    10    021                
12         -   -   No    azad1
bbcz     30    12        
03085         -   -   No    azad1 azad1222
xxaz    1    12        
azzst    1    12        
hss     2    12 

what I need to do is:

  1. Find lines starting with a number [0-9].
  2. Copy the first 5 columns separated by a space ' '.
  3. Paste it in the next lines not starting with a number.
057         -   -   No    adod3 stptazlqn    10    753
057         -   -   No    adod3     tlm    10    027        
057         -   -   No    adod3     stp    10    021                
12         -   -   No    azad1
12         -   -   No    azad1    bbcz     30    12        
03085         -   -   No    azad1 azad1222
03085         -   -   No    azad1    xxaz    1    12        
03085         -   -   No    azad1    azzst    1    12        
03085         -   -   No    azad1    hss     2    12

Thanks for any help in advance.

Cheers, Slaw


回答1:


awk to the rescue!

$ awk '{if($1+0==$1) p=$1 FS $2 FS $3 FS $4 FS $5; else $0=p FS $0}1' file | column -t

057    -  -  No  adod3  stptazlqn  10  753
057    -  -  No  adod3  tlm        10  027
057    -  -  No  adod3  stp        10  021
12     -  -  No  azad1
12     -  -  No  azad1  bbcz       30  12
03085  -  -  No  azad1  azad1222
03085  -  -  No  azad1  xxaz       1   12
03085  -  -  No  azad1  azzst      1   12
03085  -  -  No  azad1  hss        2   12

here FS is the field separator by default is the white space. Number test is done with zero addition; pipe to column for pretty formatting. The 1 at the end is the shorthand for printing the line ($0 variable)




回答2:


This might work for you (GNU sed):

sed -r '/^[0-9]/!G;s/(.*\S)\s*\n((\S+\s*){5}).*/\2 \1/;h' file

Use pattern matching to extract the fields from line beginning with an integer which will have been appended to a line that did not.

To align the columns correctly use:

sed -r '/^[0-9]/!G;s/(.*\S)\s*\n((\S+\s*){5}).*/\2 \1/;h' file | column -t


来源:https://stackoverflow.com/questions/52543683/sed-awk-perl-find-a-regex-copy-5-columns-of-this-line-and-paste-to-it-at-the-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!