Friday 15 July 2011

read a file and put the rows in seprate file due the same value of specefied column in bash -



read a file and put the rows in seprate file due the same value of specefied column in bash -

i have file named main.txt 3 columns. due column 3 value want distinguish rows , set them in separate textfiles. illustration have

12 88 sigma 15 60 beta 12 70 sigma 11 90 alpha 15 44 beta

now want read file in loop or other way due column 3 have files illustration named beta.txt contains:

15 60 beta 15 44 beta

and other files sigma.txt , on... im new bash.i dont have thought how start.how can write in bash...sorry not have codes. beforehand give thanks u kindness.

while ifs= read -r line || [[ $line ]] ; read num1 num2 name <<<"$line" printf '%s\n' "$line" >>"$name.txt" done <main.txt

set empty ifs , utilize '-r' alternative 'read' read line in 'main.txt'.

test '[[ $line ]]' handle unterminated lastly line in 'main.txt'.

use 'printf' instead of 'echo' avoid 'echo' interpreting in $line.

if don't care preserving spacing in lines, single 'read':

while read num1 num2 name || [[ $num1 ]] ; printf '%s %s %s\n' "$num1" "$num2" "$name" >>"$name.txt" done <main.txt

note output files not initialized, code append files created on first run if run more once. if problem, 1 way prepare first pass initialize output files , sec pass populate them (as above). code used initialize files:

# initialize output files new info can safely added appending while read num1 num2 name || [[ $num1 ]] ; echo -n >"$name.txt" done <main.txt

a one-pass solution possible. 1 way utilize associative array (bash 4+ only) maintain track of files have been initialized.

bash

No comments:

Post a Comment