How can I concatenate corresponding lines in two files in Perl? - perl

file1.txt
hello
tom
well
file2.txt
world
jerry
done
How to merge file1.txt with file2.txt; then create a new file - file3.txt
hello world
tom jerry
well done
thank you for reading and reply.
Attached the completed code which based on the answer.
#!/usr/bin/perl
use strict;
use warnings;
open(F1,"<","1.txt") or die "Cannot open file1:$!\n";
open(F2,"<","2.txt") or die "Cannot open file2:$!\n";
open (MYFILE, '>>3.txt');
while(<F1>){
chomp;
chomp(my $f2=<F2>);
print MYFILE $_ . $f2 ."\n";
}

if Perl is not a must, you can just use paste on *nix. If you are on Windows, you can also use paste. Just download from GNU win32
$ paste file1 file2
else, in Perl
open(F1,"<","file1") or die "Cannot open file1:$!\n";
open(F2,"<","file2") or die "Cannot open file2:$!\n";
while(<F1>){
chomp;
chomp($f2=<F2>);
print $_ . $f2 ."\n";
}

I don't think anyone should give a full answer for this.
Just open both files, then loop through both at the same time and write out to a new file.
If you don't know how to read and write files in perl, here is a tutorial:
http://perl.about.com/od/perltutorials/a/readwritefiles.htm

Related

Perl Readline on closed filehandle - file does not exist error

I am working on a simple perl program for my first assignment in my programming class. I literally have been stuck on this first part for more than a day. I cannot get my program to simply open a text file that is in the same directory as the program.
#!/usr/bin/perl -w
use strict;
my($fileName, $line);
print "Please enter name of file to be opened: ", "\n";
$fileName = <STDIN>;
chop($fileName);
#Associates FILE filehandle with the file: "filename.txt"
open(FILE, $fileName) or die("Can't open '$fileName': $!");
while(my $line = <FILE>){
print $line;
}
I am using strawberry perl. To run the program I am dragging and dropping the program into the command line to get the address of the program. It then attempts to run it.
It initially gave me a readline on closed filehandle error, and then I included the or die("Can't open '$fileName': $!"); portion of the code.
Now it says that there is no such file at the directory, but I know that the test.txt file is there because I just created it.
Picture of the code results: http://imgur.com/R8s7FFE
File directory that shows locations of my files: http://imgur.com/nUfM4lA)
The prompt is showing C:\Users\jacjar\Documents as the current working directory
So this is where the program will look for test.txt
But it is not in that directory
text.txt is in L:\College\Junior Year\1st Semester\COSC 320 (Programming Languages)
Move your test.txt file to the C: path shown above and it will work
Do you realize you are trying to open C:\User\jacjar\Documents\test.txt?

Create files from text list using command line?

I know that normally you can just use touch filename to create new files via command line. But, in the text file I have a list of about 500 cities and states, each on a new line. I need to use command line to create a new text file for each of the cities/states. For example, Texas.txt, New York.txt, California.txt
The name of the file that contains the list is newcities.txt - Is this possible to do in command line or through Perl?
You can do this directly in the shell, no need for perl
cat myfile | while read f; do echo "Creating file $f"; touch "$f"; done
perl -lnwe 'open my $fh,">", "$_.txt" or die "$_: $!";' cities.txt
Using the -l option to autochomp the input. The open will create a new empty file, and the file handle will be autoclosed when it goes out of scope.
how about a simple:
cat fileName | xargs touch
Here's a one-liner in perl, assuming each city is on a new line
perl -ne 'chomp; `touch $_`;' newcities.txt
Here's the script version:
#!/usr/bin/perl
use warnings;
use strict;
open my $fh, "<", "./newcities.txt"
or die "Cannot open file: $!";
while( my $line = <$fh> ){
chomp $line;
system("touch $line");
}
close $fh;

Perl script to copy rows to place in new file

I have a lot of text files in a folder. The folder is 'c:\vehicles'. For every text file, I want to copy any row that includes the words: model, make, year. The file I want to write to is 'vehicles.txt' and located in 'c:\'.
I know I've written the code wrong. What should I do to correct it? Thanks for the help.
C:\vehicles $ ls -A | xargs head -qn 30 | perl -Mstrict -wne 'if( $ +_ =~ /(make)|(model)|(year)/ ) { print "$_"; }' > vehicles.txt
grep -rE "(make|model|year)" c:
Perhaps the following will help:
use strict;
use warnings;
for my $file (<*.txt>) {
open my $fh, '<', $file or die $!;
while (<$fh>) {
chomp;
print "$_\n" if /(?:\b(?:model|make|year)\b)/i;
}
close $fh;
}
Assuming the script will be in c:\vehicles, type perl scriptName.pl >vehicles.txt at the command prompt.
The <*.txt> notation returns a list of all text files in the directory. Each of these files are opened and read, line by line. If any of the words your looking for are found on a line, it's printed. The >vehicles.txt notation means to print to the file.

How to get all filenames in a directory and place them in a text file with Perl?

I have been trying to write a perl script to get all of the filenames from a directory and then place each name into a text file.
I was wondering if any good perl programmers could help me out with this. Sorry if I'm asking you to write the script, but I am sure someone could figure out how to do this in only a few lines.
You might do:
perl -le 'for (glob(".* *")) {print if -f}'
If you really want to do this in Perl for some reason:
opendir DIR, '/some/dirname' or die "$!";
open FILE, '>', '/some/outputfile' or die "$!";
print FILE "$_\n" while readdir DIR;
close FILE;
closedir DIR;
edited to put newlines in the output fileā€¦ oops!
To make it more general-purpose, you could do other things with the filename, by splitting the middle bit up:
my $filename = readdir DIR;
# do something with $filename
print FILE $filename, "\n";
The first example takes advantage of Perl's $_ pronoun, instead.
But, as #Ronin420 pointed out, it's far easier to do ls -a1 /some/dirname > /some/outputfile (with stdout redirected to a file, ls will add the -1 itself, as well)

How to read multiple files from a directory, extract specific strings and ouput to an html file?

Greetings,
I have the following code and am stuck on how I would proceed to modify it so it will ask for the directory, read all files in the directory, then extract specific strings and ouput to an html file? Thanks in advance.
#!/usr/local/bin/perl
use warnings;
use strict;
use Cwd;
print "Enter filename: "; # Should be Enter directory
my $perlfile =STDIN;
open INPUT_FILE, $perlfile || die "Could not open file: $!";
open OUTPUT, '>out.html' || die "Could not open file: $!";
# Evaluates the file and imports it into an array.
my #comment_array = ;
close(INPUT_FILE);
chomp #comment_array;
#comment_array = grep /^\s*#/g, #comment_array;
my $comment;
foreach $comment (#comment_array) {
$comment =~ /####/; #Pattern match to grab only #s
# Prints comments to screen
Print results in html format
# Writes comments to output.html
Writes results to html file
}
close (OUTPUT);
Take it one step at a time. You have a lot planned, but so far you haven't even changed your prompt string to ask for a directory.
To read the entered directory name, your:
my $perlfile =STDIN;
gives an error (under use strict;). Start by looking that error up (use diagnostics; automates this) and trying to figure out what you should be doing instead.
Once you can prompt for a directory name and print it out, then add code to open the directory and read the directory. Directories can be opened and read with opendir and readdir. Make sure you can read the directory and print out the filenames before going on to the next step.
a good starting point to learn about specific functions (from the cmd line)
perldoc -f opendir
However, your particular problem is answered as follows, you can also use command line programs and pipe them into a string to simplify file handling ('cat') and pattern matching ('grep').
#!/usr/bin/perl -w
use strict;
my $dir = "/tmp";
my $dh;
my #patterns;
my $file;
opendir($dh,$dir);
while ($file = readdir($dh)){
if (-f "$dir/$file"){
my $string = `cat $dir/$file | grep pattern123`;
push #patterns, $string;
}
}
closedir($dh);
my $html = join("<br>",#patterns);
open F, ">out.html";
print F $html;
close F;