在匹配之前删除行上的回车(使用sed、tr或awk)



我正在寻找一种方法来删除行上的回车到sed匹配。例如,我想删除任何"["实例之前的回车符。

样本输入:

MESSAGE: Location
latitude
[-Pi/4,Pi/4]
longitude
[-Pi,Pi]
altitude
[10000,120000]
样本输出:

MESSAGE: Location
latitude [-Pi/4,Pi/4]
longitude [-Pi,Pi]
altitude [10000,120000]

任何使用sed、tr或awk的建议都将不胜感激。谢谢。

您可以使用Perl:

use warnings;
use strict; 
my $p; 
while (<>) {
  if (/^[/) {
    chomp $p; 
    print "$p $_";
    undef $p;
  } else {
    print $p if defined $p; 
    $p = $_; 
  }
}

或者从命令行:

perl -lane ' if (/[/) { print "$p $_"; undef $p} else { print $p if defined $p; $p = $_; }' input

快速搜索一下就会得到这个帖子的结果https://stackoverflow.com/a/1252191/722238。

使用那篇文章的解决方案来解决你的问题,这里是答案:

sed ':a;N;$!ba;s/n[/ [/g' yourinput.txt

这可能适合您(GNU sed):

sed '$!N;s/n[/ [/;P;D' file

Using awk:

awk 'NR == 1 {previous = $0}
     NR > 1 && $0 ~  "^[[]" {previous = previous $0}
     NR > 1 && $0 !~ "^[[]" {print previous; previous = $0}
     END{print previous}' your_file.txt
#!/usr/bin/awk -f
BEGIN {
  RS = ""
}
{
  gsub(/n[/, " [")
}
1

最新更新