2013-10-24 23 views
0

編號,我想知道,如果sed的是能夠做一些線計算工作,而編號特定行的,假設我有文件的符合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腳本解決方案的情況下完成這項工作?

+1

你能更清楚的知道你對「bash scrip婷「是和不是? – kojiro

+0

一個在bash中使用控制結構的程序,例如while,for等 –

+0

你想達到什麼目的?你需要做什麼?我在這裏聞到[XY-problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – sehe

回答

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 
+0

太棒了!我會學習這個perl表達式,比你! –

4

最好用來嘗試。我認爲要編號不與任何withespace字符開頭的行:

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

它產生:

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

你不介意說爲什麼用awk rathen比sed更好? –

+1

@NicoRodsevich:這是因爲'sed'不能使用變量。你在哪裏保留下一個你必須打印的號碼?難。 – Birei