STDout

Hi,

I have a program set to read in a text file, change certain characters and then print the altered version to the screen but does anyone know how to save the new version as another text file? And, if possible, how to specify the file name, and perhaps location?

Thanks!

myscript.sh inputfilename > /path/to/outfilefilename

Hi,

Try this one,

#! /usr/bin/perl

my $file = "path/inputfile";
my $outfile = "path/outfile";

if( open(IFILE, "<", "$file") )
{
    if ( open(OFILE, ">", "$outfile") )
    {
        while(my $line = <IFILE> )
        {
            chomp($line);

            ## do your changes
            print OFILE "$line\n"; ## print (or write) to the outfile since we use OFILE( this refers outfile)#
        }
    }
    else
    {
        print "Error: Unable to open file $outfile\n";
    }
}
else
{
    print "Error: Unable to open file $file\n";
}

Here IFILE, OFILE are file handlers. we can make changes of the file with the help of file handler.
Here i used three arguments open function, You can use like below. Dont confuse with this. This is just an alternate way. open file accepts three arguments.

if ( open(IFILE, "<$file") )

we can use select function to select the output stream(STDOUT or FILEHANDLE).

select(OFILE);
print "Welcome\n"; ##It will write in outfile
print "Hai\n";  ##It will write in outfile 
## Please check that i have not use File Handle but still it will write to the outfile bcos we have selected the default output stream.

After all the print statement will write to outfile since we have selected the default output stream as OFILE.
If you want to print the msg to STDOUT. You have to select,

select(STDOUT);
print "Welcome\n"; # It will print in STDOUT

Cheers,
Ranga :slight_smile: