Jump to content

File handling question.


vidyashankara

Recommended Posts

I have the following text file.
[code]
ABCD      1234            0
EFGH       5678           0
[/code]

This is what i want.

[code]
ABCD      1234       1     0
EFGH       5678      2    0
[/code]

The code should insert 1 or 2 based on the first four characters. Lets say, If the text was to have a 100 such lines, 50 ABCD. 25 EFGH and 25 XYZ, It should assign 1 to ABCD, 2 to EFGH, 3 to XYZ. There may be certain text files without ABCD, EFGH or XYZ. It can have any random 4 characters, and script must assign 1, 2, 3 in the order it shows up on the test file...

This is what i got
[code]
$input1 = file(add.txt); // read file into an array
$fp1 = f open(add.txt,'w'); // open output file for write
foreach($input1 as $line1) {

if ($line1[0]=='A') {  
    if ($line1[1]=='B') {
        if ($line1[2]=='C') {
      $line1[12] = '1';
}
}
}
if ($line1[0]=='E') {  
    if ($line1[1]=='F') {
        if ($line1[2]=='G') {
      $line1[12] = '2';
}
}
}

f write($fp1,$line1);
f close($fp1);
[/code]
The file functions are without spaces...

The problem with this script it, If something other then ABC or EFG shows up, nothing is written.
can any of you help me with this?

Thanks
Vidyashankara

It should read the letters from specific columns and write 1,2,3 ... in specfic columns.
Link to comment
Share on other sites

[!--quoteo(post=381189:date=Jun 7 2006, 06:17 PM:name=poirot)--][div class=\'quotetop\']QUOTE(poirot @ Jun 7 2006, 06:17 PM) [snapback]381189[/snapback][/div][div class=\'quotemain\'][!--quotec--]
OMG, is this some kind of very odd programming exercise?

I think regular expressions are the best way out in this case.
Remember that they are able to create backreferences, and they'll be useful.
[/quote]

Its a lot to do with chemistry. But i just changed the names to make it understandable. Can you write me the code?
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.