How do I delete the first line in a file?
I can't search for a particular string, since they're all very similar, but I'd like something simple to chop out the first 4 lines in a file.
They'开发者_开发问答re all variable length too. I've had a think about perl, and it all seems harder than I thought, but I'd like to do it in Perl, AWK or a shell command if possible.
Does anybody have a simple way of doing this?
tail -n+2 filename
Will skip the first line in filename
and output it to stdout. The -n+2
option means to start outputting lines beginning with the second line.
Of course you can substitute 2 with whatever number you need (your title and actual question content say first and fifth, respectively).
sed
is the simplest. To delete the first line of a file, do:
sed '1d' file.txt
Or, to remove the first four lines, do:
sed '1,4d' file.txt
skip first 4 lines
$ awk 'NR>4' file >temp;mv temp file
$ more +5 file >temp;mv temp file
$ perl -i.bak -ne '$.>=4 && print' file
sed -i '1,4d' <filename>
will delete the first four lines of its input file. (If you only wanted the first line deleted, you could use '1d'
instead.)
The -i
flag stands for in-place editing, which means that the input file is also the output file, and thus the changes are written back out to the original file. If you'd prefer to have the file left intact and the modified contents simply written to stdout, just omit the -i
.
This and many other sed
1-liners can be found in a handy reference here:
http://sed.sourceforge.net/sed1line.txt
tail -n +5 file > temp
mv temp file
perl -pe'1..4and$_=""'
as equivalent to
sed 1,4d
or
perl -ne'1..4or print'
as equivalent to
sed -n '1,4!p'
You can use -i
same as in sed
.
A solution which requires no scripting language (like awk, sed, perl etc.):
tail -n `expr \`cat FILE | wc -l\` - 1` FILE > FILE.new; mv FILE.new FILE
The idea is to count the number of lines in the file, then subtract one, then pass the result to the 'tail' command.
Try this: sed -i 1d file
A general rule :
To remove the n
first lines: sed '1,nd' file.txt
For example: sed '1,4d' file.txt
to remove the first 4 lines
Use File::Tie. That does just fine.
Search the file for the fourth "\r\n" or "\n" and substring from that index.
精彩评论