1
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 5 years have passed since last update.

bashを使ったシェルスクリプト上での文字列置換

Last updated at Posted at 2019-07-22

シェルスクリプトで文字を置き換えるとき、以下のようにsedコマンドを使うことが一般的だと思います。

$ sed -e 's/変更前の文字列/変更後の文字列/g' ./file.txt > ./file-new.txt

ファイル内の文字列全部を書き換えるときは確かにsedコマンドが便利だし直感的です。
実は他にもbashの標準機能を使うことで文字列単体を置換することもできるので、今回はその方法を解説します。

bashを使う

# !/bin/bash

tmp="/dir1/dir2/dir3/1234_Abcde_01.jpg.html"
echo ${tmp#/}
echo ${tmp##*/}
echo ${tmp%%.*}
echo ${tmp/d/D}
echo ${tmp//d/D}
hoge=${tmp##*/}
echo ${hoge%%.*}

例えば、上記のようなシェルスクリプトを書くと以下のように変換されます。

dir1/dir2/dir3/1234_Abcde_01.jpg.html
1234_Abcde_01.jpg.html
/dir1/dir2/dir3/1234_Abcde_01
/Dir1/dir2/dir3/1234_abcde_01.jpg.html
/Dir1/Dir2/Dir3/1234_abcDe_01.jpg.html
1234_Abcde_01

やってる処理を順番に書くと

  1. 先頭の/を取り除く
  2. 末端の/までまとめて取り除く
  3. 末尾の.を取り除く(%なら末尾から1つ目の.*を取り除く)
  4. 先頭のdDで置換
  5. 全てのdDで置換
  6. 2と3の複合型

覚えておくと、変数に代入したちょっとした文字列を変換する時に便利。
ファイル単位で変換したい時はsedのほうが使いやすそうです。

メモ

これ書いてるときに解消したエラーについて。
bash(シェルスクリプト)で条件文を書こうとしているときに

 [: =: unary operator expected

のようなエラーが出た時は以下のようにして対処。

  if [ "$var" = '' ]; then
    echo 'テストecho'
  fi  

"$var"と書くのと半角スペースを正しく記載するのがポイントのようです。
(シェルスクリプトは半角スペースや改行の指定の仕方に注意ですね)

参考

シェルスクリプトによる置換や削除
空行を検出するスクリプトを書いていた
Bash の if 文(test文)のオプションを整理してみた
Bashで正規表現マッチした文字列を取り出す

1
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
1
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?