从文件中解析具有特定模式的行

use*_*326 2 command-line bash perl

我有一个大致如下所示的文件:

[25]:0.00843832,469:0.0109533):0.00657864,((((872:0.00120503,((980:0.0001
[29]:((962:0.000580339,930:0.000580339):0.00543993 ((758:0.000598847,726:0.000598847)
position:
sites: 5 4 2 1 3 4 543 5  67 657  78 67 8  5645 6 
01010010101010101010101010101011111100011
1111010010010101010101010111101000100000
00000000000000011001100101010010101011111
Run Code Online (Sandbox Code Playgroud)

现在我只想从文件中提取以 [numeric]: 开头的那些行。它不仅是前两个,也可能是前 7 或 8 或其他。我将如何读取此文件并输出仅包含带有 [numeric]: 的行的文件?

hee*_*ayl 9

使用grep

$ grep "^\[[0-9]\+\]:" file.txt 
[25]:0.00843832,469:0.0109533):0.00657864,((((872:0.00120503,((980:0.0001
[29]:((962:0.000580339,930:0.000580339):0.00543993 ((758:0.000598847,726:0.000598847)
Run Code Online (Sandbox Code Playgroud)

要将输出保存在文件 ( output.txt) 中:

grep "^\[[0-9]\+\]:" file.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

使用python

grep "^\[[0-9]\+\]:" file.txt > output.txt
Run Code Online (Sandbox Code Playgroud)


A.B*_*.B. 5

perl方式:

perl -ne 'print "$1\n" if /^(\[[0-9]*\]:.*)/' testdata > out
Run Code Online (Sandbox Code Playgroud)

awk方式:

awk 'match($0, /^\[[0-9]*\]:/)' testdata > out
Run Code Online (Sandbox Code Playgroud)

两个命令的输出

[25]:0.00843832,469:0.0109533):0.00657864,((((872:0.00120503,((980:0.0001
[29]:((962:0.000580339,930:0.000580339):0.00543993 ((758:0.000598847,726:0.000598847)
Run Code Online (Sandbox Code Playgroud)