如何获取输入文本文件的第一行,同时从文本文件中删除该行


11

如何从文本文件中删除输入文本文件的第一行?

如果我有一个文本文件,/myPathToTheFile.txt这样

► put returns between paragraphs
► for linebreak add 2 spaces at end
► _italic_ or **bold**

我想将此行作为输出

► put returns between paragraphs

我的文本文件现在应该像这样

► for linebreak add 2 spaces at end
► _italic_ or **bold*

请注意,此操作的成本与文件大小成正比。因此,如果文件很大并且您经常执行此操作,则它将非常慢。
CodesInChaos

Answers:


13
ex -s /myPathToTheFile.txt <<\EX
1p
1d
wq
EX

要么

ex -s /myPathToTheFile.txt <<< 1p$'\n'1d$'\n'wq

或者,较少键入:

ed -s /myPathToTheFile.txt <<< $'1\nd\nwq'

哇,很好用ed ...!
qwr

10

至少使用GNU sed:

$ cat file
► put returns between paragraphs
► for linebreak add 2 spaces at end
► _italic_ or **bold**

$ sed -i '1{
w /dev/stdout
d}' file
► put returns between paragraphs

$ cat file
► for linebreak add 2 spaces at end
► _italic_ or **bold**

使用GNU sed可以将它写成单行

sed -i -e '1 {w /dev/stdout' -e 'd}' file

6

假设您要输入一个shell脚本,它将按照您的要求进行操作:

NAME=$1
head -n 1 $NAME
sed -i '1d' $NAME


2

您可以使用headtail并且mv

显示第一行:

head -1 myPathToTheFile.txt

保留最后(+2)行:

tail -n +2 myPathToTheFile.txt > file.tmp && mv file.tmp myPathToTheFile.txt

1

使用文件描述符和一些 python

{
    { 
    head -n1 >&3; 
    3>&- tail -n +1;
    3>&- python -c 'import sys; sys.stdout.truncate(sys.stdout.tell())';
    }<file 1<>file
} 3>&1

1

用头和尾。文件是target.txt

head -1 target.txt && tail -n+2 target.txt > tmp
mv tmp target.txt && rm tmp

注意:请确保当前文件夹中没有现有的文件tmp,否则它将被删除。

说明:

  • “ head -1”选择第一行
  • “ tail -n + 2 target.txt> tmp”从2nd开始(包括)选择所有行,并将它们放入tmp
  • mv用tmp覆盖原始文件
  • rm tmp将删除由此创建的tmp文件
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.