2011-03-11 64 views
1

我有以下格式文本文件裏:使用正則表達式修改文本文件裏(?AWK)

line 450 

10876 -022.6421047 -070.1866390 000882 23362.47 99 000000.00 10 202246.0 
10877 -022.6421090 -070.1866412 000882 23363.42 99 000000.00 10 202247.0 
10878 -022.6421090 -070.1866412 000882 23363.93 99 000000.00 10 202248.0 
10879 -022.6421090 -070.1866412 000882 23363.68 99 000000.00 10 202249.0 
10880 -022.6421090 -070.1866412 000882 23363.72 99 000000.00 10 202250.0 

line 460 

10872 -022.6420829 -070.1866339 000882 23424.83 99 000000.00 10 202242.0 
10873 -022.6420889 -070.1866373 000882 23413.99 99 000000.00 10 202243.0 
10874 -022.6420945 -070.1866378 000882 23393.97 99 000000.00 10 202244.0 
10875 -022.6421000 -070.1866369 000882 23375.70 99 000000.00 10 202245.0 

我需要做的就是刪除blanklines,以及各數字之間的每塊「行XXX「行,連接XXX。然後,刪除以「行」開始的每一行。爲了清楚起見,這裏是所需的輸出文件的一個例子:

10876 -022.6421047 -070.1866390 000882 23362.47 99 000000.00 10 202246.0 450 
10877 -022.6421090 -070.1866412 000882 23363.42 99 000000.00 10 202247.0 450 
10878 -022.6421090 -070.1866412 000882 23363.93 99 000000.00 10 202248.0 450 
10879 -022.6421090 -070.1866412 000882 23363.68 99 000000.00 10 202249.0 450 
10880 -022.6421090 -070.1866412 000882 23363.72 99 000000.00 10 202250.0 450 
10872 -022.6420829 -070.1866339 000882 23424.83 99 000000.00 10 202242.0 460 
10873 -022.6420889 -070.1866373 000882 23413.99 99 000000.00 10 202243.0 460 
10874 -022.6420945 -070.1866378 000882 23393.97 99 000000.00 10 202244.0 460 
10875 -022.6421000 -070.1866369 000882 23375.70 99 000000.00 10 202245.0 460 
+0

感謝大家的多樣和良好的反應。選擇第一個張貼的工作:) upvoted其餘 – 2011-03-12 19:23:31

回答

3

隨着awk(假設你的輸入是file.txt,其結果是在標準輸出):

awk ' 
/^line/ {number = $2} 
/^[0-9]/ {print $0, number} 
' file.txt 
1
$ awk '$0 == "" {} 
     $1 == "line" {line = $2} 
     {print %0, line}' infile >outfile 
3

在Perl你可以這樣做:

perl -nle 'if(/^line/){($l = $_)=~s/\D//g;}elsif(/^\d/){print "$_ $l"}' file 

Ideone Link

+0

提示,以上單線短期歡迎:) – codaddict 2011-03-11 19:48:11

+0

perl -nle'/^line(\ d +)/?$ l = $ 1:/^\ d /?打印「$ _ $ l」:1'文件。更短,但不確定這有多大貢獻。 – 2011-03-11 22:26:34

1

桑達可能不是這項工作的最佳工具,但

sed '/^$/d;/line/{s/line //;h;d;};G;s|\n||' filename 

注意,但所有你的數字線之間用空格結束;這個解決方案假設這是一個錯字,他們都應該這樣做。如果沒有應該,然後使用此:

sed '/^$/d;/line/{s/line //;h;d;};G;s|\n| |' filename 

,如果一些實力和有些人可能沒有,那麼發揮它的安全:

sed '/^$/d;/line/{s/line //;h;d;};G;s| *\n| |' filename 
1
awk '/line/{n=$2;next}NF{$0=$0 FS n;print $0}' file 

ruby -ane 'n=$F[1] if /line/; print $_.chomp + " #{n}\n" if $F.size>0 && !/line/' file