11

How can I get the first line of an input text file, while deleting that line from the text file?

If I had a text file /myPathToTheFile.txt like this

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

I'd like to get this line as an output

► put returns between paragraphs

and my text file should be now like this

► for linebreak add 2 spaces at end
► _italic_ or **bold*
  • Note that the cost of this operation is proportional to the file size. So if the file is big and you do this often, it will be very slow. – CodesInChaos Feb 25 '17 at 13:55
13
ex -s /myPathToTheFile.txt <<\EX
1p
1d
wq
EX

or

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

or, less typing:

ed -s /myPathToTheFile.txt <<< $'1\nd\nwq'
  • Wow, nice use of ed...! – qwr Feb 26 '17 at 8:13
10

At least with 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**

With GNU sed it can be written as a one-liner

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

Assuming you are asking for a shell script, this will do what you requested:

NAME=$1
head -n 1 $NAME
sed -i '1d' $NAME
5
sed -ne '1p' -e '1!s/^//w temp_file' yourfile && mv temp_file yourfile
2

You can use head , tail and mv:

Display the first line:

head -1 myPathToTheFile.txt

Keeping the last (+2) lines:

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

Using file descriptors and a little bit of 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

Using head and tail. File is target.txt

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

Note: Ensure there is no existing file tmp in the current folder, else it'll be removed.

Explanation:

  • "head -1" selects the first line
  • "tail -n+2 target.txt > tmp" selects all lines from 2nd onwards( including) and puts them in tmp
  • mv overwrites the original file with tmp
  • rm tmp will remove the tmp file thus created

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.