Search code examples
linuxawk

Split file based on a key and name the output with the key name


does any one know how to split a file based on a key and name the relatedoutput with the respective key name. Thanx in advance

Input

>mail9.country1(+):38689378-38709400
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>father
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>mother
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>son
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>daughter
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------

>mailX.countryX(+):000000-3111111110
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>father
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>mother
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>son
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>daughter
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------

Output files should be like below with their respective content

mail9.country1(+):38689378-38709400.mail

>mail9.country1(+):38689378-38709400
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>father
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>mother
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>son
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>daughter
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------

mailX.countryX(+):000000-3111111110.mail

>mailX.countryX(+):000000-3111111110
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>father
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>mother
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>son
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------
>daughter
XXXXXXXXXXXXXXXXX-----------HHHHHHHH------

Solution

  • One way with awk:

    $ awk -F'>' '$2~/^mail/{f=$2".mail";gsub(/[)(]/,"_",f)}{print > f}' file