Edit a file via shell script

Code junkies hangout here

Moderators: ChrisThornett, LXF moderators

Edit a file via shell script

Postby SSL » Thu Apr 27, 2006 3:12 pm

I'm trying to edit a file via a shell script... I have 1 script and one file. The text file is made up of 5 lines e.g.
james 1111 98987678
John 2222 848474838

the 1111 and 2222 are ID's.
I want to run my script and delete the line with the ID i specify. e.g.
./script textfile -d 2222 - this will delete line with id 2222?

How do i do this?
SSL
 
Posts: 2
Joined: Thu Apr 27, 2006 3:05 pm

RE: Edit a file via shell script

Postby crispibits » Thu Apr 27, 2006 6:45 pm

I don't want to ruin the joy of working out the whole script, but the following will delete a line where it contains 222. See if this makes sense, and take it from there...

Code: Select all
sed -e '/222/d' textfile
I'm not a spammer - honest!
User avatar
crispibits
LXF regular
 
Posts: 201
Joined: Thu Jun 30, 2005 12:33 pm
Location: Bath

Postby SSL » Wed May 03, 2006 10:08 am

Hi,

Thanks for that... I now have it working as well as other options but i'm now stuck on the final part...

I'm using sed to replace the phone number in a file.e.g.

./script 1 2222 999 (This would replace the phone number for ID 2222 to 999)? I can get it to work if i specify the new and old number in the syntax when i run the script but not when i use just the ID and new number?

Is there a command to replace just the third word?

Any ideas?

James.
SSL
 
Posts: 2
Joined: Thu Apr 27, 2006 3:05 pm

Postby crispibits » Wed May 03, 2006 12:18 pm

For this you'd use awk:
Code: Select all
awk '/^1 / {$3 = "999"} {print $0}' testfile

This means 'if the line starts with 1 followed by a space, set the third field to be 999. Regardless of what came before, print the whole line.
Awk assumes the field separator to be a space, but you can alter that using the -F flag.
I'm not a spammer - honest!
User avatar
crispibits
LXF regular
 
Posts: 201
Joined: Thu Jun 30, 2005 12:33 pm
Location: Bath


Return to Programming

Who is online

Users browsing this forum: Google [Bot] and 0 guests