Repalce of digits in one field

Hewlett-packard / HP
February 11, 2009 at 06:34:32
Specs: Windows XP, 9000/800
Hi

How can I 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".

Thanks in advance



See More: Repalce of digits in one field

Report •


#1
February 11, 2009 at 09:57:51
There must be a more elegant way to do this but I have no idea what it is.

==============================================
@echo off > newfile & setLocal EnableDelayedExpansion

for /f "tokens=1* delims=," %%a in (myfile) do (
set str=%%a
call :sub1
echo !d1!!d2!!d3!!d4!!d5!!d6!,%%b>> newfile
)

goto :eof

:sub1

set d1=!str:~0,1!
set d2=!str:~1,1!
set d3=!str:~2,1!
set d4=!str:~3,1!
set d5=!str:~4,1!
set d6=!str:~5,1!

for /L %%n in (1 1 6) do (
set /a d%%n+=1
if !d%%n! equ 10 set d%%n=0
)
goto :eof


=====================================
If at first you don't succeed, you're about average.

M2


Report •

#2
February 11, 2009 at 11:10:57
C:\>perl -F',' -ane "$,=','; $F[0] =~ tr/0123456789/1234567890/; print @F" num.csv


Report •

#3
February 12, 2009 at 00:28:57
Dears, sorry because I'm beigginer in Unix.

I tried this unix command but file2 is always empty although I didn't get any error after I put semicolon at end of each line:

perl file1 -F"," -ane '$,=',' ; $F[0] =~ tr/0123456789/1234567890/ {print ( $1","$1","$3","$4 ) }' > file2

file 2 always empty


Report •

Related Solutions

#4
February 12, 2009 at 05:11:46
The src file needs to go at the end of the command, not the beginning.

[rkb@hostname ~]$ cat file1
546720,54,1,,0,2001,1.205
324315,52,0,,0,2005,0.200

[rkb@hostname ~]$ cat file2
cat: file2: No such file or directory
[rkb@hostname ~]$ perl -F',' -ane '$,=","; $F[0] =~ tr/0123456789/1234567890/; print @F' file1 > file2
[rkb@hostname ~]$ cat file2
657831,54,1,,0,2001,1.205
435426,52,0,,0,2005,0.200

or, you could use the -i (inline edit) switch instead of the output redirection.

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

If you want to keep a backup copy of the original, you'd specify an ext with the -i switch.

-i.bak


Report •

#5
February 12, 2009 at 05:16:23
Another option would be to use awk instead of perl. There would be a slight difference in syntax with the awk solution and "nails" in the UNIX area could help with that part.

You might take a look at the man pages for awk and tr.

man awk
man tr


Report •

#6
February 12, 2009 at 05:53:56
Hi,

I tried the perl command and it worked.

Many thanks for the help.


Report •


Ask Question