LoginSignup
2
2

More than 5 years have passed since last update.

シェルスクリプト メモ

Last updated at Posted at 2016-09-13

■シェルスクリプトで実行したコマンドの結果の改行をそのままにする($() とかバッククオートでコマンドを実行時)

全体をダブルクオートでくくれば改行を残せる

下記URLを参照
http://please-sleep.cou929.nu/get-command-result-with-newline.html

●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●
● 全体をダブルクオートでくくらない時
●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●
実行シェル(gitで未追跡のものを取得してArrayにいれる)

Array=`git ls-files --other --exclude-standar`
echo ${Array[@]}

実行結果

abcde のコピー 2.txt abcde のコピー.txt abcde.txt

●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●
● 全体をダブルクオートでくくる時
●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●
実行シェル(gitで未追跡のものを取得してArrayにいれる)

Array=`git ls-files --other --exclude-standar`
echo "${Array[@]}"

実行結果

abcde のコピー 2.txt
abcde のコピー.txt
abcde.txt

■カラム指定ソート

下記を参考に
http://blog.geta6.net/post/63985316076/shellでsortコマンドを使って多重ソートする

// 指定ファイルをカンマ区切りの2つめを降順、3つめを昇順にした中身を取得(この場合、2つ目を降順に並べてから3つ目を昇順にする。)
cat ファイルパス名 | sort -t, -k2,2nr -k3,3n

# 先に3つ目からソートしたければ順番を入れ替える
// 指定ファイルをカンマ区切りの2つめを降順、3つめを昇順にした中身を取得(この場合、3つ目を昇順にしてから2つ目を降順に並べる。)
cat ファイルパス名 | sort -t, -k3,3n -k2,2nr

■ファイル内データ取得

// tailを使用して指定ファイルの2行目以降を取得
tail -n +2 ファイルパス名

■ファイル内を並び替えた先頭だけを取得

tail -n +2 ファイルパス名 | sort -t, -k2,2nr -k3,3n | head -n1

■ファイル内に1行もなかった場合のNULLチェック

変数を""""で囲ってから比較する。

val=`tail -n +2 ファイルパス名 | sort -t, -k3,3nr -k2,2nr | head -n1 | cut -d',' -f2-2`

if [ "$val" = "" ]; then
  echo null
else
  echo not null
fi

■ファイル内を並び替えた先頭だけを取得し、カンマ区切りにした2つめを取得

tail -n +2 ファイルパス名 | sort -t, -k2,2nr -k3,3n | head -n1 | cut -d',' -f2-2

■ファイル内データをループ(スペースで改行される)

for l in `tail -n +2 ファイルパス名 | sort -t, -k2,2nr -k3,3n`
do
  echo l=$l
done

■ファイル内データをループ(スペースで改行しない設定にする)

下記を参考に
http://linux.just4fun.biz/逆引きシェルスクリプト/スペースが含まれる文字列を1行として扱う方法.html

#!/bin/bash
IFS_BACKUP=$IFS
IFS=$'\n'
for l in `tail -n +2 ファイルパス名 | sort -t, -k2,2nr -k3,3n`
do
  echo l=$l
done
IFS=$IFS_BACKUP

■空ファイル作成(空ファイルによる上書き保存も可能)

下記URLを参照
http://shellscript.sunone.me/input_output.html

>file
2
2
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
2
2