perl - 用另一个字符替换每第n个(和多个)字符的出现 [英] perl - replace every nth (and multiples) occurrences of a character with another character

查看:535
本文介绍了perl - 用另一个字符替换每第n个(和多个)字符的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道任何unix命令/ perl脚本将插入一个特定的字符(可以输入十六进制(即7C)或作为实际字符(即|))在第n次重复出现的位置特定字符。
ie perl script.pl,3| data.txt
将用管道替换每3,6,9 ...等逗号。



txt在运行脚本之前具有以下内容:

  fd,3232,gfd67gf,
peas,989767,jkdfnfgjhf,
dhdhjsk,267,ujfdsy,fuyds,637296,ldosi,fduy,
873,fuisouyd,try
save,2837,ipoi
  p $ p> 
$ b fd,3232,gfd67gf |
peas,989767,jkdfnfgjhf |
dhdhjsk,267,ujfdsy | fuyds,637296,ldosi | fduy,
873,fuisouyd | try
save,2837,ipoi


解决方案

小perl黑客解决问题。使用 index 函数查找逗号,替换正确的模数和 substr 执行替换。 / p>

 使用strict; 
使用警告;

while(<>){
my $ x = index($ _,,);
my $ i = 0;
while($ x!= -1){
$ i ++;
unless($ i%3){
$ _ = substr($ _,0,$ x)。|。 substr($ _,$ x + 1);
}
$ x = index($ _,,,$ x + 1)
}
print;
}

使用运行perl script.pl file.csv



注意:您可以将 my $ i $ c> while(<>)循环,以便执行全局计数,而不是每行的单独计数。不太确定我在这方面是否理解你的问题。


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, and substr to perform the replacement.

use strict;
use warnings;

while (<>) {
    my $x=index($_,","); 
    my $i = 0; 
    while ($x != -1) {
        $i++; 
        unless ($i % 3) { 
            $_ = substr($_,0,$x) ."|". substr($_,$x+1); 
        }
        $x = index($_,",",$x + 1) 
    } 
    print;
}

Run with perl script.pl file.csv.

Note: You can place the declaration my $i before the while(<>) 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.

这篇关于perl - 用另一个字符替换每第n个(和多个)字符的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆