简体   繁体   中英

shell scripting using regular expression pattern matching

I have a file say abc.txt which contains..

<mapping number=1 name=m1> 
<transformation type=aggregator name=agg_m1> /> 
<transformation type=joiner name=j_m1 /> 
</mapping>

<mapping number=2 name=m2> 
<transformation type=router name=rtr_m2> /> 
<transformation type=joiner name=j_m2 /> 
</mapping>

I neen an output of the form of the same order. ie, i need to get name field from mapping and type and name fields from transformation "in the same order :

name=m1
type=aggregator name=agg_m1
type=joiner name=j_m1
name=m2
type=router name=rtr_m2
type=joiner name=j_m2

I have used the command 'awk' to get the output , but I am getting it of the following form which is incorrect :

name=m1
name=m2
type=aggregator name=agg_m1
type=joiner name=j_m1
type=router name=rtr_m2
type=joiner name=j_m2

I tried using 'grep' and 'sed' commands too but I am getting the desired output, because the order is not preserved. I need to the get the output where the order is preserved.

Here's one way using grep :

grep -oE "(name|type)=[^ >]* *[^ >]*" file

Results:

name=m1
type=aggregator name=agg_m1
type=joiner name=j_m1
name=m2
type=router name=rtr_m2
type=joiner name=j_m2
 perl -lne '$_=~m/^[^\s]*\s([^\/\>]*)/g;print $1' your_file

tested below:

> cat temp
<mapping number=1 name=m1>
<transformation type=aggregator name=agg_m1> />
<transformation type=joiner name=j_m1 />
</mapping>

<mapping number=2 name=m2>
<transformation type=router name=rtr_m2> />
<transformation type=joiner name=j_m2 />
</mapping>
> perl -lne '$_=~m/^[^\s]*\s([^\/\>]*)/g;print $1' temp
number=1 name=m1
type=aggregator name=agg_m1
type=joiner name=j_m1


number=2 name=m2
type=router name=rtr_m2
type=joiner name=j_m2

>

If you do not need number ,then use the below regex:

perl -lne '$_=~m/^[^\s]*\s[number=\d]*([^\/\>]*)/g;print $1' your_file

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