0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Mac】grepとsedで単語として完全一致を行う正規表現

Posted at
  • 業務等でgrepやsedを利用する際に、単語一致での検索や置換処理は非常に多いです。
  • その際に完全一致とならないケースは稀では無いです。
  • 今回は、限りなく高い確率で完全一致で行うための正規表現記法を記録します。

結果

  • 結果の記述は以下の通りです。
    • ※なおMacのBSD系のgrep及びsedで動作するものとなっています。
# データ例
$ cat data

10,30,50,100,150,250,300,500

# データ例の中から50のみをgrep。
$ cat data | grep -o '[[:<:]]50[[:>:]]'

50

# データ例の中から50のみを"一致"へ置換。
$ cat data.txt | sed 's;[[:<:]]50[[:>:]];一致;g'

10,30,一致,100,150,250,300,500

内容

  • 上記の結果例は、任意のデータに対して検索及び置換を行う処理です。
  • こちらで利用している方法は、どちらも単語を[[:<:]]単語[[:>:]]のように囲むということです

grepでの単語指定

  • そもそもgrepは単語のみではなく、行の抽出を行います。
  • 単語のみの抽出には、optionを利用して、grep -o 単語とします。
  • ただ上記のデータ例では以下のように部分一致となり、4つ抽出されます。
$ cat data | grep -o 50

50
50
50
50
  • これらの事から以下の意味がある[[:<:]]単語[[:>:]]を利用します。
    • 単語の先頭及び末尾に一致するため、前後への文字列を認識しない。

sedでの単語指定

  • sedもgrep同様にそのまま置換文字列指定では、以下のように4つ置換されます。
$ cat data.txt | sed 's;50;一致;g'

10,30,一致,100,1一致,2一致,300,一致0
  • これらの事からgrep同様に[[:<:]]単語[[:>:]]のように単語として認識させる必要があります。

まとめ

  • 上記のことから、データの重複性を意識して更なる正規表現の勉強を再認識しました。

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?