I have a file. I want to print all the lines except the last one. How can we do this with a Perl one-开发者_StackOverflow社区liner?
This is not working:
cat file|perl -lane 'print if not eof()'
My bad, this is working. I didn't look at my output closely.
seq 1 6 | perl -lane 'print if not eof()'
1
2
3
4
5
If you need to do this on the command line, you can use the shell command head
. A negative number of lines will show all but the last N lines.
head --lines=-1 filename
This is a GNU extension and won't work with BSD head, for example the stock head which comes with OS X.
For Perl, your code is basically correct but there's no need to involve cat
. Otherwise you're reading the file twice. You can pass the filename in directly. Also -l
effectively does nothing there, stripping the newline off the input and putting it back onto the output. Finally, there's no need for -a
as this wastefully splits each line into @F
which is not used.
perl -ne 'print if not eof' filename
All I can say is...
It works on my computer!
(rimshot!)
So, exactly what are you getting? Is it an error message or does the program run? Does it print out any lines?
There is a difference between eof()
and eof
which might might be causing some of your concern (although both work on my system). According to Perldoc:
An eof without an argument uses the last file read. Using eof() with empty parentheses is different. It refers to the pseudo file formed from the files listed on the command line and accessed via the <> operator. Since <> isn't explicitly opened, as a normal filehandle is, an eof() before <> has been used will cause @ARGV to be examined to determine if input is available. Similarly, an eof() after <> has returned end-of-file will assume you are processing another @ARGV list, and if you haven't set @ARGV , will read input from STDIN ; see I/O Operators in perlop
By the way, the cat
isn't needed. This is the same, and it saves you from creating an extra process:
perl -ne 'print if not eof()' < file
And, you should be able to do this:
perl -ne 'print if not eof()' file
Perhaps you have been reading this? Famous Perl One-Liners Explained
These both work for me with Perl 5.10:
cat myfile | perl -ne 'print if not eof'
cat myfile | perl -lane 'print if not eof'
What is wrong with the behavior which you are seeing?
perl -ne 'print $last;$last=$_'
perl -ne 'print unless eof'
But why does it have to be Perl? -
sed '$d'
Golfing versions:
perl -ne'print if!eof'
sed \$d
Following up on @sleeplessnerd:
perl -ne 'BEGIN{$l=undef};print $l if (defined $l); $l=$_' file.txt
精彩评论