0

I have a file like:

!Denver

Line 1
Line 2
Line 3

!New York

Line 1 
Line 2

I want to do the following - Basically pull the text with prefix ! ( like !Denver ) and append the text , less "!" to the next lines until another ! comes along with new text for proceeding lines

Denver.Line 1
Denver.Line 2
Denver.Line 3
New York.Line 1
New York.Line 2

This is part of a bigger script - but am hoping to complete the rest myself.

I found the following which i am reviewing:

So I may get an answer myself shortly.

Thanks!

Community
  • 1
  • 1
Gripsiden
  • 467
  • 2
  • 15

5 Answers5

2
 perl -ne 'if (s/^!//) { chomp; $p = $_ } elsif (/\S/) { print "$p.$_" }'  < data
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • Hi Steffan - wow , thank you - This has worked straight out of the box. Im actually looking to build in a little more , but will post additional questions - i dont want to clutter this post. thanks again! – Gripsiden Aug 12 '16 at 13:52
1
#!/usr/bin/perl
use strict;
use warnings;
my $prefix;
while (<DATA>){ #loop over data line by line
    chomp; #remove \n from line
    next unless $_; #skip empty lines
    if ($_ =~ /^!/){ #check if line starts with !
        $prefix = $_; #store line as prefix
        next; #move to next line
    }
    else{
        print "$prefix.$_\n"; #if line doesn't start with ! then add prefix
    }
}
__DATA__
!Denver

Line 1
Line 2
Line 3

!New York

Line 1 
Line 2

Demo

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
1
#! /usr/bin/perl

# good perl practice
use strict;
use warnings;

# open the file to be parsed (read only)
open(my $fh, '<', 'test.txt')
    or die "Failed to open file: $!";

my $prefix = '';

# read in the file line by line (each line assigned to $_)
while(<$fh>) {

    # skip blank lines
    next if /^$/;

    # if the line starts with ! store the rest of the line
    if(/^!(.+)$/) {

        # store the rest of the line ($1) in $prefix
        $prefix = $1;

        # remove the newline
        chomp($prefix);

    # it's a normal line, print the prefix plus line content
    } else {
        print "${prefix}.$_";
    }
}
Drav Sloan
  • 1,562
  • 9
  • 13
1

You've already accepted an answer, but this also works:

sed '/^$/d;/^!/{s/^!//;s/$/\./;h;d;};G;s/\(.*\)\n\(.*\)/\2\1/' filename
Beta
  • 96,650
  • 16
  • 149
  • 150
0

It can also be done with awk:

awk '/^\!/{town=substr($0,2)}!/^$|^\!/{print town "." $0}' file

The town is catch with the ! and is displayed if the line is not empty.

oliv
  • 12,690
  • 25
  • 45