ディレクトリ内の複数のファイルに対し、ファイル内の特定の文字列を置換するbashスクリプトの作成例です。
※目次をクリックすると目次の下部にコンテンツが表示されます。
仕様
・対象ディレクトリ
/home/user/html/
・対象ファイル
○○県.html
・出力ファイル名
○○県.html_rep
・置換内容
下記のように<table>タグにid属性を追加する形で置換します。
(置換前)
<table border=1>・・・
:
<table border=1>・・・
:
<table border=1>・・・
:
<table border=1>・・・
:
(置換後)
<table id=”id1″ border=1>・・・
:
<table id=”id2″ border=1>・・・
:
<table id=”id3″ border=1>・・・
:
<table id=”id4″ border=1>・・・
:
/home/user/html/
・対象ファイル
○○県.html
・出力ファイル名
○○県.html_rep
・置換内容
下記のように<table>タグにid属性を追加する形で置換します。
(置換前)
<table border=1>・・・
:
<table border=1>・・・
:
<table border=1>・・・
:
<table border=1>・・・
:
(置換後)
<table id=”id1″ border=1>・・・
:
<table id=”id2″ border=1>・・・
:
<table id=”id3″ border=1>・・・
:
<table id=”id4″ border=1>・・・
:
作成したbashスクリプト
#!/bin/bash
tableid=(id1 id2 id3 id4)
dir=/home/user/html/
files="$dir*"
cd $dir
for filepath in $files; do
if [ -f $filepath ] ; then
if [[ $filepath =~ .*県.*html ]]; then
fileout="$filepath"_rep
: > $fileout
i=0
while read line; do
if [[ $line =~ "<table border=1>".* ]]; then
tmp=${line#"<table border=1>"}
tmp="<table id=\"${tableid[$i]}\" border=1>"$tmp
echo $tmp >> $fileout
let i++
else
echo $line >> $fileout
fi
done < $filepath
fi
fi
done
スクリプトの説明
●ファイル内のテキストを読み込み置換
以下の記事参照。
ファイルの中身を一行ずつ読んで文字列を置換するbashスクリプト
●for文を使ってディレクトリ内のファイルに対する操作
以下の記事参照。
bashのfor文を使ってディレクトリ内のファイル一覧とディレクトリ一覧を出力
以下の記事参照。
ファイルの中身を一行ずつ読んで文字列を置換するbashスクリプト
●for文を使ってディレクトリ内のファイルに対する操作
以下の記事参照。
bashのfor文を使ってディレクトリ内のファイル一覧とディレクトリ一覧を出力