特殊文字と名前の間にスペースを含む製品名を含むファイルがあります。最後に製品コードがあります。
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がコメントで述べたように、注意すべきいくつかの注意点があります。
- コメントから:
file2
as パターンを使用すると、grep
その中のテキストは正規表現として扱われます。これは、特定の文字(たとえば、.
および*
)が予期せず一致する可能性があることを意味します。
たとえば、file2
行が含まれている場合でも一致This is a dot.
できます。This is a dotx
file1
この問題を解決するには、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.)
- @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
結果を得ることもできます。