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

后端 未结 6 1016
余生分开走
余生分开走 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 20:03

    This processes the input file one line at a time (no slurping :)
    For hex input, just pass '\x7C' or whatever, as $1

    #!/bin/bash  
    
    b="${1:-,}"                             # the "before" field delimiter 
    n="${2:-3}"                             # the number of fields in a group
    a="${3:-|}"; [[ $a == [\|] ]] && a='\|' # the "after" group delimiter
    
    sed -nr "x;G; /(([^$b]+$b){$((n-1))}[^$b]+)$b/{s//\1$a/g}
             s/.*\n//; h; /.*$a/{s///; x}; p" input_file
    

    Here it is again, with some comments.

    sed -nr "x;G    # pat = hold + pat
      /(([^$b]+$b){$((n-1))}[^$b]+)$b/{s//\1$a/g}
      s/.*\n//      # del fields from prev line
      h             # hold = mod*\n
      /.*$a/{ s///  #  pat = unmodified
              x     # hold = unmodified, pat = mod*\n
            }            
      p             # print line"  input_file
    

提交回复
热议问题