views:

257

answers:

6

Input:

F1  F2         F3         F4       F5        F6  

4   ABCDEF1234 1111111111 20090101 00:00:00  XYZ 123

Output:

4   ABCDEF1234 1111111111 20090101-00:00:00  XYZ 123

F represents fields. F4 and F5 are date fields which needs to be concatenated with a hyphen. Is there a quick Perl script that does this?

+3  A: 
printf("%-4s%s %s %s-%s  %s\n", $F1, $F2, $F3, $F4, $F5, $F6);

This answer assumes that the fields are already split up into variables $F1 .. $F6. If the data is a single string, then the regex answer is more nearly appropriate.

Jonathan Leffler
+4  A: 
s/(\d{8})\s+(\d{2}:\d{2}:\d{2})/$1-$2/
chaos
Interestingly different interpretation of the question. Of course, it could also be F[0]..$F[5] that was intended, as with the autosplit mode.
Jonathan Leffler
@chaos: I was about to post the same. :-)
Alan Haggai Alavi
+1  A: 
$str = "4   ABCDEF1234 1111111111 20090101 00:00:00  XYZ 123";
@s = split /\s/,$str;
$s[5] = join("-",$s[5],$s[6]);
splice(@s,6,1);
print join(" ",@s);
ghostdog74
+3  A: 

The input looks kind of fixed-width-y, that suggests pack and unpack.

my @F = unpack( 'A4 A11 A11 A19 A7', $input_line );
$F[3] =~ s/\d\K\s+/-/; # Use lookaround (?<=\d) if \K is not available
my $line = pack( 'A4 A11 A11 A19 A7', @F );

Then again, if it's fixed enough, you can just go:

substr( $input_line, 34, 1, '-' );
Axeman
A: 

Directly in command line:

$ perl -n -e '@fields = split; printf "%s %s %s %s-%s %s %s\n", $fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5]' input.txt > output.txt

Remember that this is equivalent to put:

#!/usr/bin/perl -w
while (<>) {
  @fields = split;
  printf "%s %s %s %s-%s %s %s\n", $fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5];
}
Eliseo Ocampos
+1  A: 

If format is with fixed column width:

perl -pe'substr$_,34,1,"-"'

Otherwise something like:

perl -ane'printf"%-4s%s %s %s-%s  %s\n",@F'
Hynek -Pichi- Vychodil
+1 (I knew that there was a shorter way!)
Eliseo Ocampos