perl - replace every nth (and multiples) occurrences of a character with another character

后端 未结 6 1010
余生分开走
余生分开走 2021-01-20 19:27

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 po

6条回答
  •  天命终不由人
    2021-01-20 19:56

    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.

提交回复
热议问题