Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a string into second to last line of a file

Tags:

bash

sed

awk

I have an question about how to insert a string into the second to last line of a file.

For example:

$ cat diff_a.txt
students
teacher
mike
john

$ cat diff_b.txt
python
bash shell
Java

Expected Result should be:

$ cat diff_b.txt
python
bash shell
mike
Java

If I use the following command, it will append string "mike" into the last line of diff_b.txt

$ grep mike diff_a.txt >> diff_b.txt
$ cat diff_b.txt
python
bash shell
Java
mike

Question:

How should I put "mike" into second to last line of diff_b.txt ?
like image 993
binbjz Avatar asked Oct 20 '25 05:10

binbjz


2 Answers

You can use sed to insert a line before a specific line, given it's position :

sed '4i\My New Line\' my_file.txt

Will insert "My New Line" on the fourth line

You can use wc -l to get the number of line in the file :

$ wc -l < my_file.txt
5

Complete example to directly answer your question :

$ cat my_file.txt
Hello
World
There is another line

$ sed -i "`wc -l < my_file.txt`i\\My New Line\\" my_file.txt

$ cat my_file.txt
Hello
World
My New Line
There is another line
  • Adding -i so sed actually edit the file
  • Using double quotes, otherwise substitution and expansion is not performed within single quotes.
  • Escaping \
like image 78
Mago Avatar answered Oct 21 '25 21:10

Mago


To read the output from any command, such as grep mike diff_a.txt, into the second-to-last line of diff_b.txt:

ed -s diff_b.txt <<< $'$-1r !grep mike diff_a.txt\nwq'

This puts ed into script mode, then feeds commands to it as if they were typed as input:

  • $' ... ' - a quoted string of:
  • $-1r - on the $ last line minus 1, r read from:
  • ! grep ... - the shell command grep ...
  • \n - end the r command with a carriage return
  • wq - write (save the file) and quit ed

This is much simpler for your example, if you already know what text you want to insert:

ed -s diff_b.txt <<< $'$-1a\nmike\n.\nwq'

Here we use the a append command (ended by a carriage return), enter the mike text (ended by a carriage return), then exit a append mode with a . (ended by a carriage return), then save and exit.

like image 27
Jeff Schaller Avatar answered Oct 21 '25 21:10

Jeff Schaller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!