0
0

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 1 year has passed since last update.

sed を使って複数ページに Google アナリティクス を埋め込む

Last updated at Posted at 2023-02-23

Google アナリティクスを使ってみようかなと思ったら、以下をしておかないといけないらしいです。

Google タグを手動でインストールする
以下は、このアカウントの Google タグです。このタグをコピーして、ウェブサイトのすべてのページのコード(

要素の直後)に貼り付けます。各ページに複数の Google タグを実装することはできません。
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-hogehoge"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-hogehoge');
</script>

ということで、これをファイルにし、ga.txt とします。

<html>
<head>
</head>
<body>
Hello!
</body>
</html>

これを file1.html とします。

r 命令

の直後に ga.txt を入れるには、
$ sed '/<head>/r ga.txt' file1.html 

sed の r 命令を使うと <head> 行の後ろに ga.txt が差し込まれます。


<html>
<head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-hogehoge"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-hogehoge');
</script>

</head>
<body>
Hello!
</body>
</html>

正規表現を使う

ところがこのやりかたでは、

<head> と書かれているだけの行が存在しないといけない。

正規表現などは使えないようだ。

なので通常の

sed "s/

/ hogehoge " file1.html

の形を元にして考える。

hogehoge の代わりに ga.txt の内容が書かれるようにしたい。

解決

以下のようにする

$ sed -i "s/\(<head[.]*>\)/\1$(cat ga.txt | tr -d '\n' | sed 's/\//\\\//g')/i" file1.html

結果

<html>
<head><!-- Google tag (gtag.js) --><script async src="https://www.googletagmanager.com/gtag/js?id=G-hogehoge"></script><script>  window.dataLayer = window.dataLayer || [];  function gtag(){dataLayer.push(arguments);}  gtag('js', new Date());  gtag('config', 'G-hogehoge');</script>
</head>
<body>
Hello!
</body>
</html>

解説

sed -i 〜〜 file1.html

file1.html に 〜〜 の処理を行い、上書きします。

s/\(<head[.]*>\)/\1〜〜/g')/i

や を 〜〜 や 〜〜 に変換します。 head は大文字小文字を問いません。

$(〜〜)

〜〜 の中身を実行し、その結果を変数に入れます。

cat ga.txt | tr -d '\n'

ga.txt の改行を取り外し、1行にします。

| sed 's/\//\\\//g'

sed に与える置換先に / が含まれていると s 命令の終了と解釈されてしまうので、\/ に変換します。

一度に複数 html を書き換える

以下のようにすればOK

g$ sed -i "s/\(<head[.]*>\)/\1$(cat ga.txt | tr -d '\n' | sed 's/\//\\\//g')/i" *.html

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?