ディレクトリ内の複数のファイルに対し、ファイル内の特定の文字列を置換する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文を使ってディレクトリ内のファイル一覧とディレクトリ一覧を出力
- bashのシェルスクリプト実行方法
- bashのシェルスクリプト プログラミング方法メモ
- bashのパイプの使い方
- bashのlist、サブシェル、コマンドブロック
- bashでの式の評価と算術演算
- bashでパターンマッチを使って条件評価
- bashのfor文で配列やセパレータ付き文字列から各要素を取り出す
- bashのfor文を使ってディレクトリ内のファイル一覧とディレクトリ一覧を出力
- bashのselect制御構造
- bashのパターンマッチ演算子の使い方
- ファイルの中身を一行ずつ読んで文字列を置換するbashスクリプト
- ディスク使用量が多いディレクトリを抽出するbashスクリプト
- ディレクトリ内の複数のファイルに対しファイル内の文字列を置換するbashスクリプト
- Bashスクリプトでmysqldumpバックアップと世代管理
- Dos攻撃など大量アクセスのログを検知するBashスクリプトを作成