file1とfile2のコードをgrepしてfile3に書き込む必要があります。

file1とfile2のコードをgrepしてfile3に書き込む必要があります。

特殊文字と名前の間にスペースを含む製品名を含むファイルがあります。最後に製品コードがあります。

file2には製品名のみがあり、コードはありません。

ファイル内を見て製品名を検索し、その製品名からコードを取得し、file3に書き込むコマンドが必要です。

私がしたいことの例のイメージは次のとおりです。ここ

はい

正しい命令を出すのに役立ちますか?

ベストアンサー1

grepマニュアルから:

-f FILE, --file=FILE
Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX .

したがって、次のコマンドは file1 の file2 で一致する行を探します。

grep -f file2 file1

次に、最初のコマンドの出力から最後のフィールドを取得します。

grep -f file2 file1 | awk '{ print $NF }' > file3

ガイドライン

@themがコメントで述べたように、注意すべきいくつかの注意点があります。

  1. コメントから:

file2as パターンを使用すると、grepその中のテキストは正規表現として扱われます。これは、特定の文字(たとえば、.および *)が予期せず一致する可能性があることを意味します。

たとえば、file2行が含まれている場合でも一致This is a dot.できます。This is a dotxfile1

この問題を解決するには、addフラグを使用して-F/--fixed-stringsパターン内のすべての文字をリテラルとして処理できます。

-F, --fixed-strings
       Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F  is specified by POSIX.)
  1. @theyが書いたように:

また、正規表現はデフォルトでは固定されません。つまり、で始まる行MM706でも始まる行と一致します QMM706

いくつかの回避策は、次のフラグを使用することです-w/--word-regexp

-w, --word-regexp
       Select  only  those  lines  containing  matches  that form whole  
       words.  The test is that the matching substring must  either  be
       at  the  beginning  of  the  line,  or  preceded  by  a non-word
       constituent character.  Similarly, it must be either at the  end
       of  the  line  or  followed by a non-word constituent character.
       Word-constituent  characters  are  letters,  digits,   and   the
       underscore.

ただし、行の先頭に表示されるパターンのみが一致することを保証していないQMM706ため、問題を部分的にのみ解決します。MM706

どちらも使用すること-Fも、-w組み合わせて目的の-f結果を得ることもできます。

おすすめ記事