我一直在研究一个shell程序,它询问你想要使用的文件的名称;然后使用其中一个选项,使用perl程序对其进行排序。我将shell程序的文件转换为perl,并对文件进行了排序。但现在我被困在将文件放回shell并将其保存到新文件中。这就是我试过的:
的Perl:
use strict;
use warnings;
my $filename = $ARGV[0];
open(MYINPUTFILE, $filename); # open for input
my (@lines) = <MYINPUTFILE>; # read file into list
@lines = sort(@lines); # sort the list
my ($line);
foreach $line (@lines) # loop thru list
{
print "$line"; # print in sort order
}
close(MYINPUTFILE);
这将打印排序列表。
仅供参考,此代码从shell脚本获取文件并使用它。这是代码
外壳:
#!/bin/bash
clear
printf "Hello. \nPlease input a filename for a file containing a list of words you would like to use. Please allow for one word per line.\n -> "
read filename
printf "You have entered the filename: $filename.\n"
if [ -f "$filename" ] #check if the file even exists in the current directory to use
then
printf "The file $filename exists. What would you like to do with this file?\n\n"
else
printf "The file: $filename, does not exist. Rerun this shell script and please enter a valid file with it's proper file extension. An example of this would be mywords.txt \n\nNow exiting.\n\n"
exit
fi
printf "Main Menu\n"
printf "=========\n"
printf "Select 1 to sort file using Shell and output to a new file.\n"
printf "Select 2 to sort file using Perl and output to a new file.\n"
printf "Select 3 to search for a word using Perl.\n"
printf "Select 4 to exit.\n\n"
echo "Please enter your selection below"
read selection
printf "You have selected option $selection.\n"
if [ $selection -eq "1" ]
then
read -p "What would you like to call the new file? " newfile #asks user what they want to call the new file that will have the sorted list outputted to it
sort $filename > $newfile
echo "Your file: $newfile, has been created."
fi
if [ $selection -eq "2" ]
then
read -p "What would you like to call the new file? " newfile2
perl sort.pl $filename
# > $newfile2 #put the sorted list into the new output file that the user specificed with newfile2
fi
if [ $selection -eq "3" ]
then
perl search.pl $filename
fi
if [ $selection -eq "4" ]
then
printf "Now exiting.\n\n"
exit
fi
感谢任何帮助,谢谢!
答案 0 :(得分:0)
如评论中所述(但转到此处回答表格):
您的Perl脚本在STDOUT上输出结果,这意味着调用shell脚本可以将其重定向到输出文件。您将使用类似于您的选项#1的东西。
变化:
perl sort.pl $filename
要:
perl sort.pl $filename > $newfile2