从一个文件中提取文本并替换到另一个文件中

从一个文件中提取文本并替换到另一个文件中

我有两个自动生成的文件。我事先不知道文件的长度是多少。

我需要编写一个脚本,它从 file#1 中的倒数第二行获取第一个单词,我们称之为 $WORDONE,并替换 file#2 中关键字后面出现的任何单词,我们称之为 $KEYWORD。 $KEYWORD 在文件#2 中仅出现一次。

也就是说,file#2 应为:

内容 ..... $KEYWORD $WORDONE 内容 ....

我也最好只使用 grep、sed 或其他从一开始就包含在大多数发行版中的工具。

答案1

还根据评论,我必须重新表述这个答案(bash中的代码)

正如评论中所建议的,如果您的目标是获取 file1 倒数第二行的第一个单词,正确的方法是

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`

更多提示:如果您正在寻找的值从一开始就已知,则不需要尾部和头部。您只需在 file1 中 grep 查找您的搜索词即可。

WORD=$(grep "search term" file1)

PS:默认 gnu grep 在找到搜索词时返回整行。

备注:
最好包含 file1 和 file2 的示例,以便为您提供更好的代码。这些只是建议;结果可能与您的实际范围不正确。

相关内容