|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Splitting files based on condition
I have a ~ delimited file with 8 or 9 columns i.e. in some cases, the 9th column is populated. If the 9th column is not null, then data needs to go to file1, if there are only 8 columns, then file2.
The if statement below does not work - all the data goes to file1.txt. Any ideas will be appreciated. Thank you. while read line do v9=`cut -f9 -d~ $filename` if [[ -n $v9 ]];then echo "$line" >> file1.txt else echo "$line" >> file2.txt fi done < $filename |
|
#2
|
||||
|
||||
|
well it's probably a bit late, but this is a good way to do it..
create a file called file1 which contains all your original data like this: Quote:
now create a new file called myprogram.pl containing this: Code:
#!/usr/bin/perl
$file1="/home/chris/bin/file1";
$file2="/home/chris/bin/file2";
$file3="/home/chris/bin/file3";
open(FILE1,"<$file1");
open(FILE2,">$file2");
open(FILE3,">$file3");
while(<FILE1>){
chomp;
@fields=split "~";
if($fields[8]=~m/.+/){
print FILE3 "$_\n";
next;
}
print FILE2 "$_\n";
}
make sure you change the path from /home/chris/bin/ to whatever your working directory is. Chmod the script and run it. It will create two new files, file2 and file3 which contain your results. hth, christo
__________________
. Spiration channels: Free scripts, programming tutorials and articles Dotcut alerts: Online Press cuttings / news alerts Clearprop: UK microlight school, wiltshire Uk dating: UK safe dating with Topdates About Christo . . |
|
#3
|
|||
|
|||
|
Quote:
Hi, perl is a fine tool, but in this simple case the old awk is quite good and efficient, as well. Try this: : awk ' BEGIN { FS = "~" } $9 == "" {print | "cat" ; next} {print | "cat >&2" } ' <<! one~two~three~four~five~six~seven~eight~ one~two~three~four~five~six~seven~eight~nine one~two~three~four~five~six~seven~eight~ one~two~three~four~five~six~seven~eight~ one~two~three~four~five~six~seven~eight~ one~two~three~four~five~six~seven~eight~ one~two~three~four~five~six~seven~eight~nine one~two~three~four~five~six~seven~eight~ one~two~three~four~five~six~seven~eight~ one~two~three~four~five~six~seven~eight~nine one~two~three~four~five~six~seven~eight~nine one~two~three~four~five~six~seven~eight~ ! This script will send all lines with empty field 9 to the stdout and all other lines in stdrerr. You can then redirect them wher ever you need. Regards ![]() |
![]() |
| Viewing: Dev Shed Forums > Operating Systems > UNIX Help > Splitting files based on condition |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|