使用sed计数并打印匹配项

时间:2019-03-07 17:18:14

标签: awk sed

文本文件中有N个字符串,我想在匹配的字符串后加上数字
例如,如果有

id, col  ,   col  ,   col   ,   col  ,  position  ,class ,sal ,empno

所以我想像

id, col_1,   col_2,   col_3,    col_4,   position ,class ,sal ,empno

我可以这样做,但是不喜欢

sed -r 's/col/col1/1;s/col/col2/2;s/col/col3/3' 

3 个答案:

答案 0 :(得分:0)

请尝试以下操作(GNU awk):

awk -F'\\s*,\\s*' 'BEGIN { OFS=", "; }     # Set input and output separators
{                                          # Main block begins
    delete(a);                             # array a is to set signs for the loop to skip changed columns
    for(i=1;i<NF;i++) {                    # outer loop
        if(!(i in a)) {                    # if the column number is in a then it is already changed
            s=1;                           # to hold the suffix number 
            for(j=i+1;j<=NF;j++) {         # inner loop
                if($i==$j){                # equals found
                    $j = $i "_" ++s;       # add suffix the equal one
                    a[j];                  # column j changed so add j to array a as key
                }
            }
            if(s>1) { $i = $i "_1"; a[i];} # s great than one means equals found so change field i
        }
    }                                      # below 1 means to print the line
}1' file

输出:

id, col_1, col_2, col_3, col_4, position, class, sal, empno

答案 1 :(得分:0)

另一个awk:

awk -vs='col' '
  BEGIN {
    FS = OFS = ","
    }
  {
    for ( i = 1 ; i <= NF ; i++ ) {
      if ( $i ~ "^ *" s " *$" ) {
        sub (s , s "_" ++j , $i )
        sub ( " *$" , "" , $i )
      }
    }
    j=0
  }1
' infile

答案 2 :(得分:0)

有了Perl,这很容易

perl -pe ' s/(col)/$1."_".++$i/ge ' file

使用您的输入

$ cat umer.txt
id, col  ,   col  ,   col   ,   col  ,  position  ,class ,sal ,empno

$ perl -pe ' s/(col)/$1."_".++$i/ge ' umer.txt
id, col_1  ,   col_2  ,   col_3   ,   col_4  ,  position  ,class ,sal ,empno

$

如果您将其包含在变量中,那么

$ A='id, col  ,   col  ,   col   ,   col  ,  position  ,class ,sal ,empno'

$ echo $A | perl -pe  ' s/(col)/$1."_".++$i/ge '
id, col_1 , col_2 , col_3 , col_4 , position ,class ,sal ,empno

$

EDIT1

要跳过最后一次出现,您可以这样做

$ perl -pe ' $t++ for(/col/g) ; s/(col)/ $i<$t-1 ? $1."_".++$i : $1 /ge  ' umer.txt
id, col_1  ,   col_2  ,   col_3   ,   col  ,  position  ,class ,sal ,empno

$

EDIT2

要运行多列,

$ cat umer2.txt
id, col  ,   col  ,   col   ,   col  ,  position  ,class , class , class, sal, empno

$ perl -pe ' @list=("col","class"); for $p (@list) { $i=0; s/($p)/$1."_".++$i/ge } ' umer2.txt
id, col_1  ,   col_2  ,   col_3   ,   col_4  ,  position  ,class_1 , class_2 , class_3, sal, empno

$
相关问题