I have an question about how to insert a string into the second to last line of a file.
$ cat diff_a.txt
students
teacher
mike
john
$ cat diff_b.txt
python
bash shell
Java
$ cat diff_b.txt
python
bash shell
mike
Java
$ grep mike diff_a.txt >> diff_b.txt
$ cat diff_b.txt
python
bash shell
Java
mike
How should I put "mike" into second to last line of diff_b.txt ?
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
$ 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
-i
so sed actually edit the file\
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 returnwq
- w
rite (save the file) and q
uit edThis 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With