2

Really need some help with this one, trying to use sed (hope this is the best solution) to replace last comma for each block of lat longs. examples below.

Original file

;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,

Resulting file

;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG;
;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG;
;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG;
4

5 回答 5

2

我会使用awk

/^;/ {if(last) print gensub(/,$/,";","",last);print; next;}
{if(last) print last; last=$0}
END {print gensub(/,$/,";","",last)}

将其保存到文件中fix.awk并运行

awk -f fix.awk < data

说明:

/^;/ {...}{...}-在所有以开头的行上执行代码;

print gensub(/,$/,";","",last)- 用变量中的最后一个替换,;保留last上一行)

print;- 打印当前行

next- 转到下一行(不要{if(last) print last; last=$0}在这一行执行)

于 2013-05-23T20:18:58.303 回答
2

一个sed解决方案:

sed -n 'N;/\n;/s/,\n/;\n/;P;$s/.*\n\(.*\),$/\1;/p;D' file

丑之处在于需要单独处理最后一行。没有它,命令将是

sed -n 'N;/\n;/s/,\n/;\n/;P;D' file
于 2013-05-23T20:22:57.353 回答
2

一种仅保存region行之间的每个块并替换最后一个逗号的解决方案:

sed -n '
    ## If first line, print and process next one.
    1 { p; b };
    ## While not match "region" line, save data to hold space and
    ## process next one. If last line avoid read next one because
    ## it would end the script.
    /^;REGION/! { H; $! b }; 
    ## Get data of hold space.
    x; 
    ## Remove leading newline created with "H" instruction.
    s/^\n//; 
    ## Substitute last comma.
    s/,$/;/; 
    ## Print all.
    p; 
    ## Remove to save next block of data.
    s/^.*$//
' infile

它产生:

;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG;
;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG;
;REGION 
SOLID,
LAT,LONG,
LAT,LONG,
LAT,LONG,
LAT,LONG;
于 2013-05-23T20:28:57.430 回答
1

试试这个 awk 行:

awk  '!/LONG,$/{if(p~/LONG,/)sub(/,$/,";",p)}
{if(p)print p;p=$0}
END{if(p~/LONG,/)sub(/,$/,";",p);print p}' file
于 2013-05-23T20:21:36.620 回答
1

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

sed '/^;/!{H;$!d};1{h;d};x;s/,$/;/' file

或以另一种方式看待它:

sed '/,$/{H;$!d};1{h;d};x;s//;/' file

如果该行不是以 开头;(或以 结尾,),则将其添加到保留空间 (HS),如果它不是最后一行,则将其删除。否则它必须以';'开头 (或不,,. ;注意当前线路现在在 HS 中。对于最后一行的边缘情况,它不会被删除并落空,并且还被替换命令所作用。

于 2013-05-23T22:03:26.433 回答