Linux 指定した文字列から文字列までのデータを取得する

Linux 指定した文字列から文字列までのデータを取得する

Linuxで、指定した文字列から文字列までのデータを取得する手順を記述してます。

環境

  • OS Rocky Linux release 8.4 (Green Obsidian)
  • shell: /bin/bash

手順

指定した文字列から文字列までのデータを取得するには、「sed -n」を使用します。

実際に、以下のhtmlファイルからheadタグ内にあるデータを取得してみます。

$ cat index.html

<html>
<head>
<title>mebee</title>
</head>
<body>
hello world
</body>
</html>

範囲を指定して「sed -n」を実行します。

$ sed -n '/<head>/,/<\/head>/p' index.html 

<head>
<title>mebee</title>
</head>

取得されていることが確認できます。

また、以下のようheadタグが2つある場合は、2つとも取得します。

$ cat index.html

<html>
<head>
<title>mebee</title>
</head>
<body>
hello world
</body>
</html>
<html>
<head>
<title>mebee</title>
</head>
<body>
hello world
</body>
</html>

実行してみます。

$ sed -n '/<head>/,/<\/head>/p' index.html 

<head>
<title>mebee</title>
</head>
<head>
<title>mebee</title>
</head>

2つとも取得されていることが確認できます。