How do I delete the first line in a file?

倾然丶 夕夏残阳落幕 提交于 2019-12-10 12:49:56

问题


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?


回答1:


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



回答2:


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).




回答3:


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



回答4:


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




回答5:


tail -n +5 file > temp
mv temp file



回答6:


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.




回答7:


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.




回答8:


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




回答9:


Use File::Tie. That does just fine.




回答10:


Search the file for the fourth "\r\n" or "\n" and substring from that index.



来源:https://stackoverflow.com/questions/2652338/how-do-i-delete-the-first-line-in-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!