Linux: extracting the first line of a file

I work with OpenWrt and a very small amount of space.

Trying to extract the first line from a file. The string should go into a variable and be deleted from the file. I can use headto put it in a variable, but I can’t use tailit because, as far as I understand, I will have to do tail file > newFileit and I don’t have space for this second file.

Does anyone know if there is a better technique?

+4
source share
6 answers

Edit: you cannot use my old answer (see below) with OpenWrt, since OpenWrt does not come with ed. What a disgrace. So, here are two methods:

Way vi

vi , :

vi -c ':1d' -c ':wq' file > /dev/null

vi :1d :wq , /dev/null. , , .

, , , :

firstline=$(head -n1 file)

vi, firstline.

. , file , .

dd

dd - . dd, , , truncate, OpenWrt. :

firstline=$(head -n1 file)
linelength=$(head -n1 file | wc -c)
newsize=$(( $(wc -c < file) - $linelength ))
dd if=file of=file bs=1 skip=$linelength conv=notrunc
dd if=/dev/null of=file bs=1 count=0 seek=$newsize

! dd truncate, .


:

ed :

firstline=$(printf '%s\n' 1p d wq | ed -s file.txt)

file.txt firstline, .

+3

sed -i -e '1 w /dev/stdout' -e '1d' file
+4

:

 head -1 file
 sed -i 1d file

, , . sponge, " " .

+2

, :

# Find the number of characters in the first line
BYTES=$(head -n 1 file | wc -c)
# Shift all the data in-place
dd if=file of=file bs=1 skip=$BYTES conv=notrunc
# Remove the extra bytes on the end
truncate -s -$BYTES file
0

( dd) - .

, :

LINELENGTH=$(head -1 test.txt | wc -c)
tail -n +2 test.txt | dd of=test.txt conv=notrunc
truncate -s -$LINELENGTH test.txt

See https://unix.stackexchange.com/a/11074/15241 for a discussion of this topic.

EDIT:

Since the file is downloaded first with curl (see comments). There is another option:

curl URL | sed -e "1w first_line.txt" -e "1d" > rest.txt
firstline=$(cat first_line.txt)
rm first_line.txt
0
source

If you have enough ram:

contents=$(cat file) 
echo "$contents" | sed -n '1 !p' > file

Alternatively use ed:

ed file
2,$wq
-2
source

Source: https://habr.com/ru/post/1545065/


All Articles