简体   繁体   中英

How to split triange brackets to couple of them?

I have file contains this

abc = <0x0 0x1>;
abc = <0x0 0x1 0x2>;
def = <0x0123 0x4567 0x89AB 0xCDEF>;
def = <0x0 0x1>;
def = <0x1 0x2 0x3 0x4>;
abc = <0x0 0x2 0x4 0x6>;
def = <0x0 0x1 0x2 0x3 0x4 0x5>;

I need to convert it to

abc = <0x0 0x1>;
abc = <0x0 0x1 0x2>;
def = <0x0123 0x4567>, <0x89AB 0xCDEF>;
def = <0x0 0x1>;
def = <0x1 0x2>, <0x3 0x4>;
abc = <0x0 0x2 0x4 0x6>;
def = <0x0 0x1 0x2 0x3 0x4 0x5>;

I need to split only triangle brackets with 4 HEX-numbers between them to couple of brackets, separated with comma, with 2 HEX-numbers inside, and only on lines which beginning with 'def = ' (or 'def = ' with any symbols before its). How I can do this with sed, awk or grep?

Could you please try following.

awk '
/def/ && match($0,/<.*>/){
  val=substr($0,RSTART,RLENGTH)
  num=split(val,array," ")
  if(num==4){
    val=array[1] OFS array[2]">, <" array[3] OFS array[4]
  }
  $0=substr($0,1,RSTART-1) val substr($0,RSTART+RLENGTH)
}
1
' Input_file

In case you want to save output into Input_file itself append > temp && mv temp Input_file in above code.

This might work for you (GNU sed):

sed -E '/^ *def =/s/(<\S+ \S+) (\S+ \S+>;)$/\1>, <\2/' file

If a line begins with def = and contains 4 fields between < and > insert >, < between the 2nd and 3rd of these fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM