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

Linuxスクリプトで文字列挿入する際、複数回実行しても1行だけ挿入できるようにする

Posted at

小ネタですが、よく使うので覚書として記事化。

普通にリダイレクトすると追記され続けてイライラ

PCセットアップ等で設定ファイルの追記等を以下のように書くことがあると思います。

write_file.sh
echo "setting_for_something" >> some_one_setting.conf

これを2度3度と実行すると、ファイルに同じ内容が追記されてうざい。

$ ./write_file.sh;./write_file.sh;./write_file.sh
$ cat some_one_setting.conf
setting_for_something
setting_for_something
setting_for_something

対処: 以前の追加分を削除しとく

回避策として、sedコマンドを使って追記設定を前もって削除。

write_file.sh
sed -i '/setting_for_something/d' some_one_setting.conf
echo "setting_for_something" >> some_one_setting.conf

これなら何度実行しても1行追加になるので気持ちすっきり

$ ./write_file.sh;./write_file.sh;./write_file.sh
$ cat some_one_setting.conf
setting_for_something
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?