簡體   English   中英

如何使用sed替換bash中0或多個空格后的命令

[英]How to use sed to replace a command followed by 0 or more spaces in bash

我不知道如何在bash變量中替換逗號,然后替換0或多個空格。 這是我所擁有的:

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

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

我想做的是將“選項”附加到“基本”。 選項是用戶輸入,可以為空或csv列表,但是該列表可以為

“ test04,test05,test06”->逗號后的空格

“ test04,test05,test06”->沒有空格

“ test04,test05,test06”->混合

我需要的是我的輸出“ base”是一個以空格分隔的列表,但是無論我嘗試什么,我的列表在第一個單詞之后都會被切斷。

我的預期是

“ test00 test01 test02 test03 test04 test05 test06”

如果您的目標是生成命令,則此技術完全是錯誤的:如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[@]}"

無需sed,bash內置了模式替換參數擴展 在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//,+( )/ }"

如果您沒有可用的bash 3.0+或不喜歡啟用extglob ,只需剝離所有將在大多數情況下可用的空格:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM