Jump to content

Home

Reg. Xpression question


RpTheHotrod

Recommended Posts

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?

Link to comment
Share on other sites

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;
}

Link to comment
Share on other sites

#!/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;

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...