如何在linux shell脚本中创建一个多字符串到单个字符串

时间:2015-07-02 05:28:14

标签: linux shell

我有一个字符串(" 50342364232,Munish鼓舞人心")但是当我把它作为输入时,它在linux shell中取3个字符串,那么如何将它作为单个字符串?我输入了像./filename" 50342364232,Munish鼓舞人心的"

2 个答案:

答案 0 :(得分:0)

如果您调用./program "50342364232 , Munish inspiring"之类的程序(包括引号),那么它将被解释为program的单个参数。但是,如果在program范围内执行类似调用other-program $1的操作,则在展开$1时,它将作为多个参数进行扩展。要解决此问题,您可能希望将其作为other-program "$1"调用,这将将其保留为单个参数。

答案 1 :(得分:0)

如果您的意思是从命令行开始,只需使用$ @ build in array reference,并确保引用它,例如:

$ 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

如果你的意思是,如何在你的脚本中捕获它,以后能够以它的方式提取它,我加载一个数组(引用,见下文),然后使用索引生成功能庆典。如果您使用'!'在引用整个数组时,在左大括号和数组变量名称之间" [@],"而不是解析为值,它解析为数组的索引。

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!