文件的行编号与sed

时间:2013-10-24 22:07:21

标签: regex bash shell sed awk

我想知道sed是否能够在编号特定行时进行一些行计数工作,假设我有文件

  Some question 
         some answer
         another answer
  Another question
         another answer
         other answer

我想要一个将其转换为:所需输出

的命令
  1_ Some question 
         a_ some answer
         b_ another answer
  2_ Another question
         a_ another answer
         b_ other answer

这可以用 sed 吗?如果没有,如果没有bash编写解决方案脚本怎么办呢?

2 个答案:

答案 0 :(得分:4)

最好尝试使用。我假设您想要编号不以任何空间字符开头的行:

awk '$0 !~ /^[[:blank:]]/ { print ++i "_", $0; next } { print }' infile

它产生:

1_ Some question
         some answer
         another answer
2_ Another question
         another answer
         other answer

答案 1 :(得分:4)

Perl有一个方便的功能,++适用于角色:

perl -lpe '
    /^\S/ and do {$inner_counter="a"; s/^/ ++${outer_counter} . "_ "/e}; 
    /^\s/ and s/^\s+/$& . ${inner_counter}++ . "_ "/e
' file
1_ Some question

     a_ some answer

     b_ another answer

2_ Another question

     a_ another answer

     b_ other answer