write a variable to a file on the end of a specific line

Posted on

Problem :

I want to add a variable to the end of a specific line in file file.txt. My code so far:

#!/bin/bash    
read -p "What is the path of the repo? > " input
echo :$input  >> file.txt

I want it to add it to the end of line 2. For example,

file.txt
--------
before -
1.stuff 
2./home/retep/awesome

after -
1.stuff
2./home/retep/awesome:/home/retep/cool

Solution :

It’s another one-liner for awk:

#!/bin/bash    
read -p "What is the path of the repo? > " input

awk -v addition="$input" -v targetline=2 '
NR==targetline { print $0 ":" addition; next}
{print }' file.txt > file.tmp
mv file.tmp file.txt

Leave a Reply

Your email address will not be published.