Nico Rodsevich
Nico Rodsevich

Reputation: 2575

File's line numbering with sed

I would like to know if sed is capable of doing some line counting work while numbering specific lines, suppose I have the file

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

I want a command that transforms that into: Desired Output

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

Is that possible with sed? If not, how can that be done without bash scripting a solution?

Upvotes: 0

Views: 84

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

Perl has a handy feature that ++ works on characters:

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

Upvotes: 4

Birei
Birei

Reputation: 36252

It's better to try with . I assume that you want to number lines that don't begin with any withespace character:

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

It yields:

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

Upvotes: 4

Related Questions