2016-09-01 14 views
1

bash変数に0個以上のスペースが続くカンマを置き換える方法がわかりません。ここにあるもの:bashで0以上のスペースが続くコマンドを置き換えるためにsedを使用する方法

base="test00 test01 test02 test03" 
options="test04,test05, test06" 

for b in $(echo $options | sed "s/, \+/ /g") 
do 
    base="${base} $b" 
done 

私がしようとしているのは、「ベース」に「オプション」を追加することです。オプションしかし、そのリストが

"test04、test05、test06" することができ、空またはCSVリストすることができ、ユーザ入力されている - >スペースコンマの後

"test04、test05、test06" - >スペースなし

「test04、test05、test06」 - >私は必要なものを混合

は、しかし、関係なく、私は私のリストは、最初の単語の後に切断ばかり続けてみてくださいどのようなリストを区切らない空間とするために、私の出力「ベース」です。

私のうち期待が

ある "test00 TEST01 TEST02 TEST03 test04 test05 test06"

+0

「sed」を試してみてください。\ +は '1つ以上の空白を意味します。 0以上の空白 ' – Sundeep

+0

これは「コマンド」とは何が関係していますか?文字列を書式化するのではなく、シェルでコマンドを生成しようとする場合は、完全に異なるテクニックを使用したいと考えています(詳細については、[BashFAQ#50](http://mywiki.wooledge.org/BashFAQ/050)を参照してください) 。 –

+0

@spasic私は期待外を加えました。 –

答えて

4

SED、bashがパターン置換parameter expansionに建てられたの必要はありません。 bash 3.0以降では、extglobはより高度なサポートを追加しましたregular expressionsあなたが可能なbashの3.0+を持っていないか、extglobを有効に気に入らない場合

# Enables extended regular expressions for +(pattern) 
shopt -s extglob 

# Replaces all comma-space runs with just a single space 
options="${options//,+()/ }" 

、単にほとんどの時間を動作するすべてのスペースを取り除く:

# Remove all spaces 
options="${options// /}" 

# Then replace commas with spaces 
options="${options//,/ }" 
+0

すべての空白を削除してもうまく動作しました –

6

あなたの目標は発生している場合コマンドは、このテクニックは完全に間違っています:BashFAQ #50で説明されているように、コマンド引数は空白で区切られた文字列ではなく配列に格納されます。

base=(test00 test01 test02 test03) 
IFS=', ' read -r -a options_array <<<"$options" 

# ...and, to execute the result: 
"${base[@]}" "${options_array[@]}" 

言った、でもこれは、多くの合法的なユースケースに十分ではありません:あなたはリテラルの空白が含まれているオプションを渡したい場合はどうなるかを考えてみましょう - 例えば、./your-base-command "base argument with spaces" "second base argument" "option with spaces" "option with spaces" "second option with spaces"を実行しています。そのためには、次のようなものが必要です:

base=(./your-base-command "base argument with spaces" "second base argument") 
options="option with spaces, second option with spaces" 

# read options into an array, splitting on commas 
IFS=, read -r -a options_array <<<"$options" 

# trim leading and trailing spaces from array elements 
options_array=("${options_array[@]% }") 
options_array=("${options_array[@]# }") 

# ...and, to execute the result: 
"${base[@]}" "${options_array[@]}" 
関連する問題