5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cut コマンドで連続した空白による区切りを処理したい

Last updated at Posted at 2018-09-14

こんにちは。
cut コマンドは一個の文字を区切りとしますので、連続した空白などによる区切りを処理できなくて残念です1。そこでtrの助けを借りた後に cut へ渡すシェルスクリプトを作りました(cut.sh)。

実行例

ただし同様なことを awk 2, set, read を使って比較すると、それらの方が素直かもしれません3

$ echo ' 1  2 3 ' | ./cut.sh -f2
2
$ echo ' 1  2 3 ' | awk '{print $2}'
2
$ echo ' 1  2 3 ' | (set $(cat); echo $2)
2
$ echo ' 1  2 3 ' | (read a b c; echo $b)
2
$ echo ' 1  2 3 ' | (read -a arr; echo ${arr[1]})
2

複数行処理

さらに read コマンドで複数行処理してみると、

$ echo -e ' 1  2 \n3 4' | while read a b; do echo $b; done
2
4
$ echo -e ' 1  2 \n3 4' | while read line; do set $line; echo $2; done
2
4
$ echo -e ' 1  2 \n3 4' | while read -a arr; do echo ${arr[1]}; done
2
4

同様の処理を set および xargs -L1 を使って行ってみましたが、少し苦しいです。

$ echo -e ' 1  2 \n3 4' | sed -E 's/ +$//' | xargs -L1 -I% sh -c 'set %; echo $2'
2
4

ソース

cut.sh
#!/bin/sh
while [ $# -gt 0 ]
do
  case "$1" in
    '-f'* )
      list="$(echo $1 | sed 's/^-f//')"
      [ -z $list ] && list="$2" && shift
      shift
      ;;
  esac
done

cat "$@" | tr -s ' ' | sed -e 's/^ //' | cut -d ' ' -f $list
  1. cut はタブ区切りがデフォルトという少し珍しいコマンドです。

  2. awk では -F'[ ]' と指定すると、一個の空白による区切り処理となります。

  3. 参考記事:「bashで文字列分解する時、cutやawkもいいけど、setの方が早い、けどreadが最強

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?