Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl snippet equivalent to an AWK statement 3

Status
Not open for further replies.

powahusr

Technical User
Jan 22, 2001
240
0
0
US
I would like to write a comparable snippet of Perl code as to the awk statement bellow that was written for use within the UNIX Korn Shell. I’m somewhat intermediate to this stuff and could use some help. Thanks in Advance!

Awk to Perl conversion


awk '{ print $2, $1 }' $TMP1 > $TMP2
 
it's a bit longer in Perl than in awk, I usually use awk for one-liners like this.

put the following code in a file (called my_file - say), chmod +x the file and the run it like this:

my_file $TMP1 > $TMP2

!#/bin/perl

while(<>){
@input = split(/\s+/,$_);
print &quot;$input[1], $input[0]\n&quot;;
}
Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
Worked great, but I left out one piece of important information.

I would like everything done from within the script file:

Lets say I set $TMP1=foo1.txt and the file &quot;foo.txt&quot; contained 1 line of data containing the saying, &quot;Hello World&quot;. I simply want to kick this script off by typing, &quot;Perl my_file&quot;. In effect a file called foo2.txt gets created and it's contents read, &quot;World, Hello&quot;.

How would the structure of the snippet change now?

Thanks for your help!
 
change it like so:[tt]
#!/usr/bin/perl

my $file1 = &quot;whatever.txt&quot;;
my $file2 = &quot;output.txt&quot;;

open INPUT, &quot;<$file1&quot;;
open OUTPUT, &quot;>$file2&quot;;

while (<INPUT>)
{
@input = split(/\s+/,$_);
print OUTPUT &quot;$input[1], $input[0]\n&quot;;
}
close INPUT;
close OUTPUT;
[/tt]

that means you'd have to change the script every time you wanted to change which files you used. is this what you meant? &quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
Perfect, Yep did exactly what I wanted it to do. Thanks!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top