Computing.Net > Forums > Unix > Replace one digit within a field

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Replace one digit within a field

Reply to Message Icon

Name: Zaid_2000
Date: February 11, 2009 at 22:17:32 Pacific
OS: Windows XP
CPU/Ram: 8000/9000
Product: Hewlett-packard / HP
Subcategory: General
Comment:

Hello,

I need an answer using unix awk, sed, or perl commands to replace certain digits within one field through the file. ex. "1" to be replaced with "2", "2" to be replaced with "3", and so on.
The original file looks like this:

546720,54,1,,0,2001,1.205
324315,52,0,,0,2005,0.200

and it should be like this:

657831,54,1,,0,2001,1.205
435426,52,0,,0,2005,0.200

In the example I just add +1 for all digits, or "1" is replaced by "2" untill "9" is replaced by "0".

Sorry this was answered in Programming category but I need in Unix, the answer using perl didn't work.


Thanks in advance




Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: February 12, 2009 at 08:50:58 Pacific
Reply:

I must respectfully disagree with you. The perl solution that Fishmonger provided in the Programming forum definitely DOES work:

perl -F',' -ane '$,=","; $F[0] =~ tr/0123456789/1234567890/; print @F' file1

That said, here is a Korn shell unix script which reads file1 using a while loop. For each line it parses the first field and the rest of the line using the comma as a field separator. I then change field 1 to your requirement using the Unix translate, tr, command. I then glue the line back together sending the output to file2.

#!/bin/ksh

while IFS="," read f1 fx
do
   f1=$(echo "$f1"| tr [0123456789] [1234567890])
   echo "$f1,$fx"
done < file1 > file2

Personally, I like the perl solution better.


0
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: Replace one digit within a field

finding length of a field in shell www.computing.net/answers/unix/finding-length-of-a-field-in-shell/7053.html

pg a file within a script www.computing.net/answers/unix/pg-a-file-within-a-script/6503.html

Passing a field separator literally www.computing.net/answers/unix/passing-a-field-separator-literally/4656.html