0

我想知道 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 脚本解决方案的情况下做到这一点?

4

2 回答 2

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
于 2013-10-24T22:33:52.013 回答
4

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

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

它产生:

1_ Some question
         some answer
         another answer
2_ Another question
         another answer
         other answer
于 2013-10-24T22:31:57.700 回答