PDA

View Full Version : Reg. Xpression question


RpTheHotrod
10-20-2008, 04:24 PM
I have a text file that has a load of information such as

■Field1■|■Field2■|■Misc■
■ABC001■|■ABC005■|■123■
■ABC006■|■ABC009■|■123■
■ABC010■|■ABC012■|■123■

and I'm trying to swap what's in Field1 with Field2.

I've been going through looking at replace regex, but I have not yet gotten to the point where the light bulb turns on. Any ideas?

Det. Bart Lasiter
10-20-2008, 09:18 PM
dunno how you'd use a regex since in that example the data from the fields have the same format. i'd just read the file line by line into variables for the fields then use fprintf or whatever the equivalent is in the language you're using to write the line back with the field values switched. this code will work on a table formatted as:

|8 char string|8 char string|4 char string|


#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *fp;
if((fp=fopen("table.txt", "r+")) == NULL){return 0;}

char *field1, *field2, *field3;
field1 = malloc(9);
field2 = malloc(9);
field3 = malloc(5);

fscanf(fp, "|%8s|%8s|%4s|", field1, field2, field3);
rewind(fp);
fprintf(fp, "|%s|%s|%s|\n", field2, field1, field3);
fclose(fp);

return 0;
}

tk102
10-20-2008, 10:08 PM
#!/usr/local/bin/perl
my $original_file = 'blahblah.txt';
my $new_file = 'new.txt';
open OLDFH,"<",$original_file;
open NEWFH,">",$new_file;
while ($line=<OLDFH>) {
chomp $line;
$line =~ /þ(.*?)þ\|þ(.*?)þ(.*)/;
$newline = "þ$2"."þ|þ".$1."þ$3\n";
print NEWFH $newline;
}
close OLDFH;
close NEWFH;

IG-64
10-20-2008, 10:32 PM
http://imgs.xkcd.com/comics/regular_expressions.png (http://xkcd.com/208/)

That's about all I can add to this discussion.

tk102
10-20-2008, 10:57 PM
Download sed for Windows if that's your OS (link) (http://gnuwin32.sourceforge.net/packages/sed.htm)

sed "s#\([0-z]*\)þ|þ\([0-z]*\)þ|þ\([0-z]*\)#\2|\1|\3#" c:\oldfile.txt > c:\newfile.text