Does anyone know any unix commands/perl script that would insert a specific character (that can be entered as either hex (ie 7C) or as the actual character (ie |)) in the position of the nth recurring occurence of a specific character.
ie perl script.pl "," 3 "|" data.txt
would replace every 3rd,6th,9th...etc comma with a pipe.
So if data.txt had the following before the script was run:
fd,3232,gfd67gf,
peas,989767,jkdfnfgjhf,
dhdhjsk,267,ujfdsy,fuyds,637296,ldosi,fduy,
873,fuisouyd,try
save,2837,ipoi
It should then have this after the script was run:
fd,3232,gfd67gf|
peas,989767,jkdfnfgjhf|
dhdhjsk,267,ujfdsy|fuyds,637296,ldosi|fduy,
873,fuisouyd|try
save,2837,ipoi
Small perl hack to solve the problem. Using the
index
function to find the commas, modulus to replace the right one, andsubstr
to perform the replacement.Run with
perl script.pl file.csv
.Note: You can place the declaration
my $i
before thewhile(<>)
loop in order to do a global count, instead of a separate count for each line. Not quite sure I understood your question in that regard.If the
$from
and$to
parameters have different length, you still need to mess a bit with the second parameter ofsubstr
to make it work correctly.How about a nice, simple
awk
one-liner?One minor bug just occurred to me: it will print a
,
or|
as the very last character. To avoid this, we need to alter it slightly:This processes the input file one line at a time (no slurping :)
For hex input, just pass
'\x7C'
or whatever, as$1
Here it is again, with some comments.
I have an idea in bash script :
That will do the trick.