質問

I'm looking for a way to remove carriage returns on the line prior to the sed match. For example, I'd like to remove the carriage return prior to any instance of "[".

Sample input:

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

Sample output:

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

Any suggestion using sed, tr or awk would be appreciated. Thanks.

役に立ちましたか?

解決

You can use Perl:

use warnings;
use strict; 

my $p; 

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

Or from the command line:

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

他のヒント

A quick search would have yielded the result to this post https://stackoverflow.com/a/1252191/722238.

Using the solution from that post with your problem, here is the answer:

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

This might work for you (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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top