I need your help with formate a txt file using bash/linux. The file looks like the following, it always has a line called Rate: Sth then it follows with the details in the very specific format. I'd like to split the file up with one rate for each file. In this example, I'd like to have 3 file, and each has the corresponding line says what the Rate value was.
How will you approach this?
line No. Main Text
1 Rate: GBP
2 12/01/1999,90.5911501,Validated
.....
.....
210 18/01/1999,90.954996,Validated
211 Rate: RMB
212 24/04/2008,132.2542,Validated
.....
1000 25/04/2008,132.2279,Validated
1001 28/04/2008,131.69915,Validated
1002 Rate: USD
1003 21/11/11,-0.004419534,Validated
The csplit command is used to split any file into many parts as required by the user. The parts are determined by context lines. Output pieces of FILE separated by PATTERN(s) to files 'xx00', 'xx01', …, and output byte counts of each piece to standard output.
This might work for you:
csplit -z -f 'temp' -b '%02d.txt' file /Rate/ {*}
This will produce files temp00.txt, temp01.txt...
If you only want the Rate
line then;
sed -i '/Rate/!d' temp*.txt
I'd do this in perl:
#!/usr/bin/perl
use strict;
use warnings;
open (my $out, ">-") or die "oops";
while(<>)
{
if (m/^Rate: (\w+)/o)
{
close $out and open ($out, ">$1") or die "oops";
next;
}
print $out $_
}
Use it like
perl ./test.pl input.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With