S
S
sbh2018-04-10 05:06:42
linux
sbh, 2018-04-10 05:06:42

How to insert a line in a file before the last line?

You need to insert a line in the file before its last line.
How it is better to implement it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ildar Saribzhanov, 2018-04-10
@Bluz

There is a multi-word option

#!/bin/bash

NEED_STR='penultimate line'

FILE='need_file_path'

LAST=$(tail -1 $FILE)
sed -i '$ d' $FILE
echo "$NEED_STR" >> $FILE
echo "$LAST" >> $FILE

It could probably be shorter, but I can't think of it.

I
Igor, 2018-04-10
@assembled

AWK script, takes the string to be inserted as an argument, redirect I / O to the necessary files:

BEGIN {
   s = "\n"
}

{
    if ( s != "\n" ) print s ;
    s = $0 ;
}

END {
    print ARGV [ 1 ] ;
    print s ;
}

X
xibir, 2018-04-10
@xibir

sed -i '$iстрока' /tmp/file.txt

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question