0

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.

  • does it have to be a bash script, or would any scripting language be OK? (zsh, ksh, perl, awk, etc) – Jeff Schaller Jan 19 '17 at 19:50
  • It doesn't have to be bash. I'll update the question – V.Vocor Jan 19 '17 at 19:59
0

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 -F"words 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.