简体   繁体   English

如何在Linux Shell脚本中将多字符串转换为单字符串

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

Am having a string like ("50342364232 , Munish inspiring") but when am giving this as input it is taking as 3 string in linux shell so how to make it as a single string ? 我有一个类似(“ 50342364232,Munish inspiring”)的字符串,但是当将其作为输入时,它在Linux shell中以3字符串的形式出现,那么如何使其成为单个字符串呢? i gave the input like ./filename "50342364232 , Munish inspiring " 我给了类似./filename“ 50342364232,Munish inspiring”的输入

If you invoke a program like ./program "50342364232 , Munish inspiring" , including the quotes, then it will be interpreted as a single argument to program . 如果调用诸如./program "50342364232 , Munish inspiring" (包括引号),则它将被解释为program的单个参数。 However, if within program you do something like call other-program $1 , then when $1 is expanded, it will be expanded as multiple arguments. 但是,如果在program执行类似调用other-program $1 ,则在扩展$1时,它将扩展为多个参数。 To work around that, you would want to invoke it as other-program "$1" , which will preserve it as a single argument. 要解决此问题,您希望将其作为other-program "$1"来调用,这会将其保留为单个参数。

If you mean from the command line, just use the $@ build in array reference, and be sure to quote it, eg: 如果您是从命令行中获取,则只需使用$ @内置数组引用,并确保将其引用即可,例如:

$ 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

Output: 输出:

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

If you mean, how do you capture that in your script with the ability to extract it later the way you got it, I'd load an array (quoted, see below), then use the index generation feature in bash. 如果您的意思是,如何在脚本中捕获它并能够在以后获取它的方式中提取它,那么我将加载一个数组(引用,请参阅下文),然后在bash中使用索引生成功能。 If you use a '!' 如果您使用'!' between the opening brace and array variable name when referencing the entire array "[@]," instead of resolving to the values, it resolves to the indexes of the array. 引用整个数组“ [@]”时,在大括号和数组变量名之间切换,而不是解析为值,而是解析为数组的索引。

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

Output: 输出:

$ 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