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?

【Linux】コマンドを使用してファイルに書き込む

0
Posted at

はじめに

コマンドを使用してファイルに書き込む主な方法について調べた結果をまとめます。

echoコマンドで一行を書き込む

echo コマンドの主な用途

引数で与えられた文字列(主に一行の文字列)を表示・出力する

ファイルに新規書き込む/上書き

$ echo "Hello, world!" > hello.txt
  • ファイルが存在しない場合、新しく作成される
  • ファイルがすでに存在する場合、既存のファイルを上書きする

ファイルに追記

$ echo "Hello, world!"  >> hello.txt
  • ファイルが存在しない場合、新しく作成される
  • ファイルがすでに存在する場合、既存のファイルに追記する

cat コマンドで複数行を書き込む

catコマンドの主な用途

引数で与えられたファイルの中身を表示・出力する

ファイルに複数行を書き込む/上書き

$ cat << EOF > hello.txt
Hello, Taro!
Hello, Hanako!
EOF
  • << EOF はヒアドキュメントの開始を示す
  • 以降の行はEOF という文字列が出るまで、ひとまとまりの入力として扱われる
  • > hello.txtcat の出力をhello.txtにリダイレクトする

ファイルに複数行を追記する

$ cat << EOF >> hello.txt
Hello, Taro!
Hello, Hanako!
EOF

補足

teeコマンドで書き換える

teeコマンドの主な用途

入力を標準出力に表示し、同時にファイルに書き込む

  • 一行を書き込む + 標準出力
$ echo "Hello, world!" | tee hello.txt
  • 一行を追記する + 標準出力
$ echo "Hello, world!" | tee -a hello.txt
  • 複数行を書き込む/上書き + 標準出力
$ cat << EOF | tee hello.txt
Hello, Taro!
Hello, Hanako!
EOF
  • 複数行を追記する + 標準出力
$ cat << EOF | tee -a hello.txt
Hello, Taro!
Hello, Hanako!
EOF

中身を書かずにファイルを作る

$ > hello.txt
# >> hello.txtも同じ

ファイルの中身を書き換えて保存する

sedコマンドの主な用途

テキストを読み込んで変換・編集する

sed -i 's/Hello/Hi/g' hello.txt
  • hello.txt中の文字列"Hello"を"Hi"に置き換える
    • -i : ファイルを置き換える(上書き保存)
       - -i.bak : バックアップファイル hello.txt.bakを自動生成する
    • s/old/new/g
      • s: substitute(置換)
      • old: 検索したい文字列
      • new: 置き換える文字列
      • g: グロバール置換。一行の中に文字列oldが複数ある場合すべて置換する
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?