I have two auto-generated files. I do not know in advance what the lengths of the files are going to be. I need to write a script which takes the first word from the penultimate line in file#1, let's call it $WORDONE, and replace whatever word comes AFTER a keyword, let's call it $KEYWORD, in file#2. $KEYWORD only appears once in file#2. That is, file#2 should read:content ..... $KEYWORD $WORDONE content ....   I would also preferably only use grep, sed or other tools which are included in most distros from the start. 
Extract text from one file and replace in the other
bash;shell script;text processing;sed;grep
According also to the comments i have to rephrase this answer (code in bash)As advised in comments if your goal is to get the first word of the penultimate line of file1 the correct way is WORDONE=$(tail -n2 file1 |head -n1 |grep 'REGEX Expression to get 1st word')#or even this way that i tend to personally prefer:WORDONE=$(tail -n2 file1 |head -n1 |awk -Fwords delimiter '{print $1}')#tail will isolate the last two lines and then head will get the first of them = one line before end.# In case of grep you need to built a regulare expression to give you the first word of this line.# In case of awk you need to define the delimiter between words in this line (space, comma, etc) and awk will return to you the first word.#To append wordone to a keyword in file2 you can use:sed s#$KEYWORD#$KEYWORD $WORDONE# file2#You can use g at the end of sed for global replacement of all $KEYWORD appearances. #Otherwise only the first $KEYWORD will be replaced.#To write replacement immediately to the file2 use `sed -i`More tips:If the value you are looking for is known from the beginning you don't need tail and head. You just grep for your search term in file1.WORD=$(grep search term file1)PS: Default gnu grep returns the whole line when the search term is found.Remark:It would be better to include samples of file1 and file2 to give you a better code. These are just advises; results could be incorrect for your real scope.