gsub command - UNIX shell

October 26, 2011 at 05:19:50
Specs: Windows XP
Hi,
I have a pipe delimeted file and I need to change the value in field 9 positon 9 for a length of 2. Here's the command I'm using but not working, can someone help.
IFS="|"
awk '{
if (substr($9, 9,2) == "01")
replace( substr($9, 9,2), "04");
if (substr($9, 9,2) == "06")
replace( substr($9, 9,2), "09");
print;
}' ROBOUT1.TXT > ROBOUT2.TXT

The input file look like this:
STAGEDATA |1 |104099999|99800099| -13.57|2011-10-15|2011-10-13|2009-06-01|2009-06-01
STAGEDATA |1 |104199999|95000299| 0.00|2011-10-15|2011-10-14|2011-08-01|2011-08-06
and need the ouput file to like:
STAGEDATA |1 |104099999|99800099| -13.57|2011-10-15|2011-10-13|2009-06-01|2009-06-04
STAGEDATA |1 |104199999|95000299| 0.00|2011-10-15|2011-10-14|2011-08-01|2011-08-09
just the last 2 fields in the file need to change.



See More: gsub command - UNIX shell

Report •

#1
October 27, 2011 at 16:42:19
awk can extract characters from a given position using the substr function, but it does not replace characters at a given position. How about a perl script that splits the line into 9 fields (start counting from 0) and checks the postions?

If your perl script is named myperl.pl, execute this way provided you are in the same directory as ROBOUT1.TXT:

myperl.ss ROBOUT1.TXT ROBOUT2.TXT

#!/usr/bin/perl

use warnings;
use strict;

my $src = shift @ARGV;
my $dest = shift @ARGV;

open(IN, '<', $src) or die "Cannot open inputfile $src: $!\n";
open(OUT, '>', $dest) or die "Cannot open outputfile $dest: $!\n";
while (<IN>) {
   #
   chomp;

   (my $f0, my $f1, my $f2, my $f3, my $f4, my $f5, my $f6, my $f7, my $f8) = split /\|/, $_;

    my $s1 = substr($f8, 8, 2);
    if ($s1 eq "01")
       {
       substr($f8, 8, 2)= "04";
       }

    if ($s1 eq "06")
       {
       substr($f8, 8, 2)= "09";
       }

    print OUT "$f0|$f1|$f2|$f3|$f4|$f5|$f6|$f7|$f8 \n";
}

close IN;
close OUT;


Report •

#2
October 28, 2011 at 04:55:38
Thanks Nails, that worked but I was suprised that we can't do this in AWK.

Report •
Related Solutions


Ask Question