簡體   English   中英

如何在Linux Shell腳本中將多字符串轉換為單字符串

[英]how to make a multiple string to single string in linux shell scripting

我有一個類似(“ 50342364232,Munish inspiring”)的字符串,但是當將其作為輸入時,它在Linux shell中以3字符串的形式出現,那么如何使其成為單個字符串呢? 我給了類似./filename“ 50342364232,Munish inspiring”的輸入

如果調用諸如./program "50342364232 , Munish inspiring" (包括引號),則它將被解釋為program的單個參數。 但是,如果在program執行類似調用other-program $1 ,則在擴展$1時,它將擴展為多個參數。 要解決此問題,您希望將其作為other-program "$1"來調用,這會將其保留為單個參數。

如果您是從命令行中獲取,則只需使用$ @內置數組引用,並確保將其引用即可,例如:

$ malx "50342364232 , Munish inspiring" "some other, literal string" "and yet... one more" |sed 's/^/    /' # pad4 for forum
for larg in "$@";do
  ((++ct))
  echo "Local Arg $ct:  $larg"
done

輸出:

Local Arg 1:  50342364232 , Munish inspiring
Local Arg 2:  some other, literal string
Local Arg 3:  and yet... one more

如果您的意思是,如何在腳本中捕獲它並能夠在以后獲取它的方式中提取它,那么我將加載一個數組(引用,請參閱下文),然后在bash中使用索引生成功能。 如果您使用'!' 引用整個數組“ [@]”時,在大括號和數組變量名之間切換,而不是解析為值,而是解析為數組的索引。

argary=("$@")    # command-line args
# can continue to add to array locally:
argary+=("Brown eggs"
         "are local eggs, and"
         "local eggs are fresh!")
for ix in ${!argary[@]};do
  echo "Element $ix:  ${argary[ix]}"
done

輸出:

$ malx2 "50342364232 , Munish inspiring" "some other, literal string" "and yet... one more" |sed 's/^/    /' # forum formating
Element 0:  50342364232 , Munish inspiring
Element 1:  some other, literal string
Element 2:  and yet... one more
Element 3:  Brown eggs
Element 4:  are local eggs, and
Element 5:  local eggs are fresh!

暫無
暫無

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

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