Lefora Free Forum
Loading
1250 views

How to parse a text file

Page 1
1–9
rookie - member
1 posts

Hi every one!!

I'm a newbe with Cocoa :S so I'm having a lot of problems with it.

I would like to know how to open a text file and parse it, searching lines with regular expressions and changing the content.
For more detail I will explain whats my idea:

I want to make a program that parses the /etc/hosts file and change lines on it depending on the content it has.

/etc/hosts    contain
__


##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1 localhost

255.255.255.255 HOLA

--

I would like to find "HOLA" and change the line to "HELLOW":

Result of /etc/hosts after running the program:

__
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 HELLOW
--

I've been searching a lot but I didn`t find anything.

Thanks!!!

PD: Sorry about my poor english :(

?
63 posts



Hi kwyjybo

I suggest you look at NSFileHandle, NSData and NSString at http://developer.apple.com/library/mac/navigation/

You could use a CLI program such as this (note, isn't perfect):

#import <Foundation/Foundation.h>
int main (int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSError* idc;
    NSString* str = [NSString stringWithContentsOfFile:@"/etc/hosts" encoding:NSUTF8StringEncoding error:&idc];
    if (idc) {
        NSLog(@"/etc/hosts was not readable");
    }
    NSMutableString* mStr = [NSMutableString stringWithString:str];
    [mStr replaceOccurrencesOfString:@"HOLA" withString:@"HELLOW" options:nil range:NSMakeRange(0, [mstr length])];
    [mStr writeToFile:@"/etc/hosts" atomically:YES encoding: NSUTF8StringEncoding error: &idc];
    if (error) {
        NSLog(@"/etc/hosts was not readable");
    }
    [pool drain];
    return 0;
}

__________________
kompilesoft

come and see my website! it's real cool reviews
?
63 posts

Here's the actual code:

#import <Foundation/Foundation.h>


int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

if (argc != 4) {

NSLog(@"Syntax: snr <file> <search> <replace>");

return 3;

}

NSError* idc;

NSArray* args = [[NSProcessInfo processInfo] arguments];


int fail = 0;

    NSString* str = [NSString stringWithContentsOfFile:[[args objectAtIndex:1] stringByStandardizingPath] encoding:NSUTF8StringEncoding error:&idc];

    if (idc) {

        NSLog(@"%@ was not readable", [args objectAtIndex:1]);

fail = 1;

    }

    if (fail == 0) {

idc = nil;

NSMutableString* mstr = [NSMutableString stringWithString:str];

[mstr replaceOccurrencesOfString:[args objectAtIndex:2] withString:[args objectAtIndex:3] options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mstr length])];

[mstr writeToFile:[args objectAtIndex:1] atomically:YES encoding: NSUTF8StringEncoding error: &idc];

if (idc) {

NSLog(@"%@ was not writable", [args objectAtIndex:1]);

fail = 2;

}

}

    [pool drain];

    return fail;

}

__________________
kompilesoft

come and see my website! it's real cool reviews
?
288 posts



K's code looks about correct to me as a cocoa approach to this task.

In the UNIX world, it's more common to use a bash script to do this kind of thing.  The "active ingredient" is sed (stream editor).  So you could say:

sed s/old-pattern/new-string/g /etc/hosts

And he'll, write a new hosts file to standard output.  It's kind of fun really, try it from the terminal.  However I'd like to caution you about /etc/hosts.  That's a system file and you'll need to use sudo to get the privileges to update the file.  Be sure to make a backup copy of the file before you start messing with it.  For example sudo cp /etc/hosts /etc/hosts.orig

I've written a little bash script to show you one style of packaging sed inside a script.  I called the script editHosts.sh and put it in my private bin (which is on the path).  Use it at your own risk - and play with it on a copy of the hosts file before you even think about letting near the system's file.  For example:

$ cd ~
$ cp /etc/hosts hosts
$ sudo chown $USER hosts
$ chmod +x editHosts.sh
$ ./editHosts.sh hosts foo   brickyard

#!/bin/bash
##
# editHosts.sh  path-to-hosts old new
#
##
##
# Parse command line
if [ ${#*} -ne 3 ]; then
    echo syntax: editHosts.sh file old new
    exit 1
fi
##
# setup some variables
hosts="$1"
old="$2"
new="$3"
tmp=/tmp/editHosts
result=0
##
# test the input
if [ ! -e "$hosts" ]; then
    echo $hosts does not exist
    exit 2
fi
##
# do the business
cat "$hosts" > "$tmp"
sed "s/$old/$new/g" "$tmp" > "$hosts"
result=$?
exit $result
# That's all folks!
##

__________________
?
63 posts

For more, I recommend you buy Programming in Objective-C 2.0 by Stephen Kochan (for the language) and Cocoa® Programming for Mac® OS X™ (Cocoa). Both excellent books I learnt from.

__________________
kompilesoft

come and see my website! it's real cool reviews
?
288 posts

Kompilesoft and I have collaborated and produced a tutorial about this matter.  I've also extended K's code to support regular expressions in the input file. http://clanmills.com/articles/cocoatutorials/RegularExpressions.pdf

You can download the code from http://clanmills.com/articles/cocoatutorials/RegularExpressions.zip

__________________
?
63 posts

I never knew of the existence of this document.

__________________
kompilesoft

come and see my website! it's real cool reviews
?
288 posts

Sometimes I wonder what you guys are smokin' up there in Canada !

I apologise for confusing you.  I said I was going to do this - however I only sent you an email about the same time that I posted the message above on the board.  So I think you must have seen the forum message before you read my email saying "job done".

__________________
?
63 posts

We smoke engines at Davesfarm :)

I have no problem with your regex tutorial. Just confused me for a second!

__________________
kompilesoft

come and see my website! it's real cool reviews
Page 1
1–9

Locked Topic


You must be a member to post in this forum

Join Now!