3

我有多个文本文件中的数据,如下所示:

1  DAEJ             X            -3120041.6620      -3120042.0476     -0.3856      0.0014               
                    Y             4084614.2137       4084614.6871      0.4734      0.0015               
                    Z             3764026.4954       3764026.7346      0.2392      0.0014               

                    HEIGHT            116.0088           116.6419      0.6332      0.0017      0.0017    8.0
                    LATITUDE     36 23 57.946407    36 23 57.940907   -0.1699      0.0013      0.0012   57.5      0.0012   62.9
                    LONGITUDE   127 22 28.131395   127 22 28.132160    0.0190      0.0012      0.0013    2.3      0.0013

我想通过过滤器运行它,以便输出如下所示:

DAEJ: 36 23 57.940907, 127 22 28.132160, 116.6419

我可以很容易地使用 grepWin 使用命名捕获通过搜索:

(?<site>\w\w\w\w+)<filler>\r\n\r\n<filler>(?<height>\-?\d+\.\d+)<filler>(?<heightRMS>\d+\.\d+)<filler>\r\n<filler>(?<lat>\-?\ *\d+\ +\d+\ +\d+\.\d+)<filler>(?<latRMS>\d+\.\d+)<filler>\r\n<filler>(?<lon>\-?\ *\d+\ +\d+\ +\d+\.\d+)<filler>(?<lonRMS>\d+\.\d+)<filler>

并替换为(忽略未引用的组,我将在其他实现中使用它):

$+{site}: $+{lat}, $+{lon}, $+{height}

但当然,代价是通过 GUI 手动完成。我想知道是否有一种方法可以通过将 pcregrep 输出传输到 sed 以进行文本替换来编写脚本?我知道与pcregrep -M上面的多行正则表达式模式匹配的选项,并且在那之前我一直是成功的,但是我被问题的sed结尾所困扰。

4

2 回答 2

3

我将awk用来处理您的文本文件:

awk '$1 ~ /^[0-9]+$/ { printf "%s: ", $2 } $1 == "HEIGHT" { height = $3 } $1 == "LATITUDE" { printf "%s %s %s, ", $2, $3, $4 } $1 == "LONGITUDE" { printf "%s %s %s, %s\n", $5, $6, $7, height }' file.txt

为了便于阅读,在多行上拆分:

$1 ~ /^[0-9]+$/ { 
    printf "%s: ", $2
}

$1 == "HEIGHT" {
    height = $3
}

$1 == "LATITUDE" {
    printf "%s %s %s, ", $2, $3, $4
}

$1 == "LONGITUDE" {
    printf "%s %s %s, %s\n", $5, $6, $7, height
}

结果:

DAEJ: 36 23 57.946407, 127 22 28.132160, 116.6419

编辑:

将以下代码放入名为 的文件中script.awk

$3 == "X" {
    printf "%s: ", $2
}

$1 == "HEIGHT" {
    height = $3
}

$1 == "LATITUDE" {
    if ($2 == "-" && $6 == "-") { printf "-%s %s %s, ", $7, $8, $9 }
    else if ($2 == "-") { printf "%s %s %s, ", $6, $7, $8 }
    else if ($5 == "-") { printf "-%s %s %s, ", $6, $7, $8 }
    else { printf "%s %s %s, ", $5, $6, $7 }
}

$1 == "LONGITUDE" {
    if ($2 == "-" && $6 == "-") { printf "-%s %s %s, %s\n", $7, $8, $9, height }
    else if ($2 == "-") { printf "%s %s %s, %s\n", $6, $7, $8, height }
    else if ($5 == "-") { printf "-%s %s %s, %s\n", $6, $7, $8, height }
    else { printf "%s %s %s, %s\n", $5, $6, $7, height }
}

像这样运行:

awk -f script.awk file.txt
于 2012-07-26T06:30:16.807 回答
0

这可能对您有用(GNU sed):

sed '/^DAEJ/,/^\s*LONGITUDE/!d;/HEIGHT/{s/^\s*\S*\s*\S*\s*\(\S*\).*/\1/;h};/LATITUDE/{s/^\s*\(\S*\s*\)\{4\}\(\(\S*\s*\)\{2\}\S*\).*/\2/;H};/LONGITUDE/!d;s/^\s*\(\S*\s*\)\{4\}\(\(\S*\s*\)\{2\}\S*\).*/ \2/;H;g;y/\n/,/;s/\([^,]*\),\(.*\)/DAEJ: \2, \1/' file1 file2 filen
于 2012-07-26T08:23:26.417 回答