0
1

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

シェルスクリプトでファイルの中身を順に取得

Last updated at Posted at 2020-06-02

1.やりたいこと
2.コード紹介
3.実行例

やりたいこと

ファイルの中身を取得して上から順番に処理していきます。
本記事ではファイル内の名前データ(name.txt)の中身を上から取得して、通し番号をつけてcsv(name.csv)に変換するループ文のシェルスクリプトを紹介します。

コード紹介

現在のフォルダの状況

実行前の状態
$ cat name.txt
Taro Suzuki
Jiro Suzuki
Noriko Yamada
Junko Nishida
main.sh
# !/bin/sh
cnt=1

cat name.txt | while read data
do
	echo ${cnt},${data} >> name.csv
	#cnt変数のインクリメント
	cnt=`expr ${cnt} + 1`
done

実行例

main.shの実行
sh main.sh
実行後の状況
$ cat name.csv
1,Taro Suzuki
2,Jiro Suzuki
3,Noriko Yamada
4,Junko Nishida
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?