見出し画像

【シェルスクリプト】ファイルを量産するの巻

またしても誰トク情報を展開している、おばちゃんです。

まあ、おばちゃんが学んだことを書き連ねる日記なのだから、こういうものだということで。

はてさて、今回のお題は、あるテンプレートの中のタイトル部分とファイル自体の名前を入れ替えながら、ファイルを量産するというシェルスクリプト。

・・・自分で書いてるのに意味わからんな。

ようは、あるファイル(template.php)があって、

<?php
/**
 * template.php
 */

get_header();
?>

<main id="primary" class="site-main">
  <article class="content">
    <header class="page-header">
      <h1 class="page-title">タイトル</h1>
    </header>
  </article>
  <?php get_template_part( 'plugins/swiper/swiper-gallery' ); ?>
</main>

<?php
get_footer();

この中の「タイトル」の部分を、シェルスクリプトの配列(titles)の文字に入れ替えては、配列(filenames)をファイル名として保存していくという感じ。

で、書いたのがこちら↓(touch.sh

前提:macOS Ventura(ver.13.1)上のzsh GNU sed導入済み

# touch.sh
#!/bin/zsh

titles=(
"バルバラ異界"
"マージナル"
"11人いる!"
"スターレッド"
"ウは宇宙船のウ"
)

filenames=(
"otherworld-barbara"
"marginal"
"they-were-eleven"
"star-red"
"u-wa-uchuusen-no-u"
)

for ((i=1; i<=${#filenames[*]}; i++))
do
	title=${titles[$i]}
	filename=${filenames[$i]}
	sed -e "s/タイトル/$title/" ./template.php > tmp
	cp template.php $filename.php
	mv tmp $filename.php
done

で、実行

zsh touch.sh

↓こんな感じに「タイトル」の文字がそれぞれに入れ替えられた5つのファイルが出来上がる。

(略)
      <h1 class="page-title">バルバラ異界</h1>
(略)
otherworld-barbara.php
marginal.php
they-were-eleven.php
star-red.php
u-wa-uchuusen-no-u.php

ちなみに吊るしのターミナルだとsedが思ったように動いてくれなかったから、GNU版を導入しました。(MacのsedはBSD系なのだそうです。参考にしたサイトがLinux使いばかりだったから?)

% sed --version
sed (GNU sed) 4.9
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

sedの書き方が、いまいちよくわからん・・・


WEBデザイナー(自営業)のおばちゃんです。最近はBlenderネタ多めです。