Text-Processing

如何通過 AWK/…增加行開始替換的行計數器?

  • December 30, 2016

我首先想到了 SED ( sed "s/^/COUNTER \&/" /tmp/1.tex),但它是為單行設計的,我不能通過 sed 來增加計數器本身,所以現在想,因為我在集成方法awk方面有豐富的經驗。gawk數據

What & South Dragon & North Dragon    & 5 \\ \hline
What & South Dragon & North Dragon    & 5 \\ \hline
What & South Dragon & North Dragon    & 5 \\ \hline

預期產出

1 & What & South Dragon & North Dragon    & 5 \\ \hline
2 & What & South Dragon & North Dragon    & 5 \\ \hline
3 & What & South Dragon & North Dragon    & 5 \\ \hline

作業系統:Debian 8.5

nl是一個對文件的行進行編號的實用程序。用法:

nl /path/to/file

在您的具體情況下:

$ nl  -s ' & ' input.txt                                                                                                 
    1 & What & South Dragon & North Dragon    & 5 \\ \hline
    2 & What & South Dragon & North Dragon    & 5 \\ \hline
    3 & What & South Dragon & North Dragon    & 5 \\ \hline

這實現了你所追求的。(一樣awk '$0=NR" & "$0' filename,但這有點神秘)

awk '{print NR,"&",$0}' filename
1 & What & South Dragon & North Dragon    & 5 \\ \hline
2 & What & South Dragon & North Dragon    & 5 \\ \hline
3 & What & South Dragon & North Dragon    & 5 \\ \hline

或者,如果sed更可取,這會給出相同的結果。

sed = filename | sed 'N;s/\n/ \& /'

perl方法。

perl -pe '$_="$. & $_"' filename
perl -pe 's/^/$. & /' filename

引用自:https://unix.stackexchange.com/questions/333097