Insert content of a file to another file at a line number which is given by third file

Hi friends, here is my problem.

I have three files like this..

cat file1.txt

unix is best 
unix is best 
linux is best
unix is best
linux is best
linux is best
unix is best
unix is best

cat file2.txt

Windows performs better
Mac OS performs better
Windows performs better
Mac OS performs better

cat file3.txt

6

I want to insert content of file2.txt into a file1.txt at a linenumber given by file3.txt.. :wink:

OUTPUT should be

unix is best 
unix is best 
linux is best
unix is best
linux is best
Windows performs better
Mac OS performs better
Windows performs better
Mac OS performs better
linux is best
unix is best
unix is best

can you please suggest me one liner shell command to achieve above task..

Hi,
under linux and shell bash:

$ sed -e "$((`<file3.txt` -1))rfile2.txt" file1.txt
unix is best
unix is best
linux is best
unix is best
linux is best
Windows performs better
Mac OS performs better
Windows performs better
Mac OS performs better
linux is best
unix is best
unix is best

Regards.

2 Likes

Hello Jagadeesh Kumar,

Welcome to forums, please use code tags as per forum rules for your codes/Inputs/commands which you are using into your posts. Following may help you in same.

awk -vval=`cat Input_file3.txt` 'NR==val{system("cat Input_file2.txt");} 1'  Input_file1.txt

Output will be as follows.

unix is best
unix is best
linux is best
unix is best
linux is best
Windows performs better
Mac OS performs better
Windows performs better
Mac OS performs better
linux is best
unix is best
unix is best
 

Thanks,
R. Singh

2 Likes

Try also

awk 'NR == 1 {LC = $0; next} FNR == LC {while (0 < getline X < FI) print X} 1' file3 FI="file2" file1
unix is best 
unix is best 
linux is best
unix is best
linux is best
Windows performs better
Mac OS performs better
Windows performs better
Mac OS performs better
linux is best
unix is best
unix is best
2 Likes

With a recent shell, try

sed "$(($(cat file3)-1))rfile2"  file1
1 Like