pogibas
pogibas

Reputation: 28379

Split file into multiple according to variable content

I want to split file according to it's content.
My dummy file looks like that:

info   info    info    cat
info   info    info    cow
info   info    info    dog
info   info    info    dinosaur 
info   info    info    bat

$4 words starts with different letters (C,D,B) - I want to split file into multiples according to the first letter of $4.
Preferable output (3 different files) looks like that:

file_c

info   info    info    cat  
info   info    info    cow

file_d

info   info    info    dog
info   info    info    dinosaur 

file_b

info   info    info    bat

Hope someone can help me with this.

Upvotes: 1

Views: 191

Answers (4)

Mirage
Mirage

Reputation: 31568

Using Python

with open("temp.txt","r") as f:
     for line in f.readlines():
        col = line.split()[3][0]
        filename = "file_"+col
        f2 = open(filename,"a")
        f2.write(line)
f2.close()

Upvotes: 0

Kent
Kent

Reputation: 195269

this oneliner should work:

awk '{print $0 > "file_"substr($4,0,1)}' yourfile

Upvotes: 5

Vijay
Vijay

Reputation: 67319

awk '{name="file_"substr($4,0,1);print >name}' your_file

tested below:

> cat temp
info   info    info    cat
info   info    info    cow
info   info    info    dog
info   info    info    dinosaur 
info   info    info    bat
> awk '{name="file_"substr($4,0,1);print >name}' temp
> cat file_b
info   info    info    bat
> cat file_c
info   info    info    cat
info   info    info    cow
> cat file_d
info   info    info    dog
info   info    info    dinosaur 

Upvotes: 3

Lev Levitsky
Lev Levitsky

Reputation: 65861

$ while read a b c d; do echo $a $b $c $d >> file_${d:0:1}; done < dummy.txt 

Upvotes: 2

Related Questions