6
6

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 1 year has passed since last update.

bash | 正規表現で連続したスペースを削除する

Last updated at Posted at 2015-12-09

問題

スペースの連続を削除したい。

test.sh
#!/bin/bash 

echo '   abc' | sed 's/\s+//g'
echo '   abc' | sed 's/\s*//g'
echo '   abc' | sed 's/ +//g'
echo '   abc' | sed 's/ *//g'

結果

4番目だけ動く。

   abc
   abc
   abc
abc

解決

-E オプションで拡張正規表現を有効にしよう。

test.sh
#!/bin/bash 

echo '   abc' | sed -E 's/\s+//g'
echo '   abc' | sed -E 's/\s*//g'
echo '   abc' | sed -E 's/ +//g'
echo '   abc' | sed -E 's/ *//g'

下の二つは動くようになる。

   abc
   abc
abc
abc

補足

本記事のコメントも参照のこと。(ありがとうございます)

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

6
6
3

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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?