文字列のsed

[sed] 実行して理解 sedコマンドで対象ファイルに改行を追加

前書き

このリポジトリでは、sedコマンドを実行して対象ファイルの指定した行番号に改行を入れます

インストールする必要のあるコマンド

  1. git

クイックスタート

上記のコマンドをインストール済みの方は、以下のコマンドを実行してリポジトリからダウンロード後、ディレクトリを移動し、sedコマンドを実行して対象ファイルの指定した行番号に改行を入れられます

ubuntu

git clone https://github.com/trygfmi/sed_newline.git
cd sed_newline
cat hello_ubuntu.txt
sed -i '1i\
' hello_ubuntu.txt
cat hello_ubuntu.txt

macos

※MacPortsを使用しています

git clone https://github.com/trygfmi/sed_newline.git
cd sed_newline
cat hello_macos.txt
sed -i '' '1i\
\
' hello_macos.txt
cat hello_macos.txt

windows

※MSYS2 MINGW64を使用しています

git clone https://github.com/trygfmi/sed_newline.git
cd sed_newline
cat hello_windows.txt
sed -i '1i\
' hello_windows.txt
cat hello_windows.txt

実行手順

ubuntu

クリックして詳細を開く

事前確認

以下のコマンドを端末に打ち込んでcommand not foundが出なければokです

git --version

preinstall

command not foundが出たコマンドを以下のコマンドでインストールしてください

sudo apt install git

コマンド

以下のコマンドを実行することで詳細のような挙動になります

git clone https://github.com/trygfmi/sed_newline.git
cd sed_newline
cat hello_ubuntu.txt
sed -i '1i\
' hello_ubuntu.txt
cat hello_ubuntu.txt
詳細


hello ubuntu

macos

クリックして詳細を開く

事前確認

以下のコマンドをターミナルに打ち込んでcommand not foundが出なければokです

source ~/bashrc_folder/macports_alias
git --version

※macosはMacPortsパッケージマネージャを使用してコマンドを管理します。もしインストールしていない方は以下のリンクからMacPortsのインストール手順をご覧ください

またコマンドに別名を設定して既存の環境と競合しないでコマンドを呼び出せるようにします。

初めてこのブログを利用する方は、以下の2つの記事を参考に環境構築してください

preinstall

command not foundが出たコマンドを以下のコマンドでインストールしてエイリアスを設定してください

sudo port install git
echo 'alias git="/opt/local/bin/git"' >> ~/bashrc_folder/macports_alias

コマンド

以下のコマンドを実行することで詳細のような挙動になります

source ~/bashrc_folder/macports_alias
git clone https://github.com/trygfmi/sed_newline.git
cd sed_newline
cat hello_macos.txt
sed -i '' '1i\
\
' hello_macos.txt
cat hello_macos.txt
詳細


hello macos

windows

クリックして詳細を開く

事前確認

以下のコマンドをMSYS2 MINGW64に打ち込んでcommand not foundが出なければokです

git --version

※windowsはMSYS2 MINGW64で確認しています。もしインストールしていない方は以下のリンクからmsys2のインストール手順をご覧ください

https://ss523971.stars.ne.jp/todo/2025/10/02/windows-msys2%e3%82%92%e3%82%a4%e3%83%b3%e3%82%b9%e3%83%88%e3%83%bc%e3%83%ab%e3%81%99%e3%82%8b%e3%81%be%e3%81%a7%e3%81%ae%e6%89%8b%e9%a0%86

preinstall

command not foundが出たコマンドを以下のコマンドでインストールしてください

pacman --sync git

コマンド

以下のコマンドを実行することで詳細のような挙動になります

git clone https://github.com/trygfmi/sed_newline.git
cd sed_newline
cat hello_windows.txt
sed -i '1i\
' hello_windows.txt
cat hello_windows.txt
詳細


hello windows

後書き

各行末に\(バックスラッシュ)を記述するのがポイントです。macosに関しては、-iオプションの後にバックアップファイルを指定する必要があり、必要ない場合は”でokです

この記事で使用したコマンドで実行できるお薦め記事

この記事で使用しているキーボード

投稿者: user

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です