Click to See Complete Forum and Search --> : Basic Unix programming!


muk
March 1st, 2006, 01:46 PM
Hi, I am a newcomer to unix programming and am stuck on something.

Basically the question is that I am required to do is "update the contents of a file by replacing all matches of the word ''user' with the number '1156'. This number also needs to go at the beginning of each line. If the command completes successfully it should print 'YES' else it should print 'NO'.

This has to be done using pipelining and it would be really helpful if its not too complex as I have just started learning unix!

I have tried a few commands using grep, egrep and tr which have given me some of the answers but my main problem is getting the number at the beginning of each line. Here's what I've done :


egrep -i user test.txt | tr 'user' '1156' | more

But this changes the letters within user (u,s,e,r) in any word. So if the file test.txt contained the words "help me user" the result would be something like:

h11p m5 1156

Can somebody please help me solve this problem?

Thanks!

Marc G
March 4th, 2006, 05:13 AM
Take a look at the man page of sed which allows you to use regular expressions to do find and replace operations.

muk
March 5th, 2006, 09:04 PM
Hi, thanks for the reply.

I have looked at the sed command within the unix manual and it has given me an idea of what to do but there are not many options within this command. Do I have to use grep or egrep with this command or is it possible to just use sed?

Thanks again

Marc G
March 7th, 2006, 03:41 PM
Something like:
sed -r "s/^(.*)user(.*)$/1156 \11156\2/g" test.txt
When you run this on test.txt which is:
lijn 1
lijn user bla
end
the result will be:
lijn 1
1156 lijn 1156 bla
end