あるファイルからテキストを抽出して別のファイルに置き換えます。

あるファイルからテキストを抽出して別のファイルに置き換えます。

自動生成されたファイルが2つあります。ファイルの長さがどのくらいになるかは事前にわかりません。

file#1の2行目から最後の行までの最初の単語を取得して$ WORDONEと呼び、file#2のキーワードの後に​​表示されるすべての単語を置き換えるスクリプトを作成する必要があります。 $KEYWORDと言います。 $ KEYWORDはファイル#2に一度だけ表示されます。

つまり、file#2 は次のようになります。

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

また、最初からほとんどのディストリビューションに含まれているgrep、sed、またはその他のツールを使用する方が良いでしょう。

ベストアンサー1

また、コメントに基づいてこの回答を書き直す必要があります(bashのコード)。

コメントで提案したように、目標がfile1の最後から2行目の最初の単語を取得することである場合、正しい方法は次のとおりです。

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の例を含めることをお勧めします。これは単なる提案であり、実際の範囲では結果が正しくない可能性があります。

おすすめ記事