Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何将字符串中的项拆分为两个,其中一个包含以';开头的项-D';?_Bash_Shell - Fatal编程技术网

Bash 如何将字符串中的项拆分为两个,其中一个包含以';开头的项-D';?

Bash 如何将字符串中的项拆分为两个,其中一个包含以';开头的项-D';?,bash,shell,Bash,Shell,我正在编写一个shell,其他人可以将参数传递给它,例如: someshell task1 task2 -Daaa=111 -Dbbb=222 task3 在shell中,我可以使用$@获取所有参数,即: task1 task2 -Daaa=111 -Dbbb=222 task3 然后我想从字符串中提取所有以-D开头的参数,并生成两个字符串: -Daaa=111 -Dbbb=222 及 我不熟悉bash,我现在可以做的是拆分字符串并检查每个项目,然后以某种方式将它们分组。这似乎有点复杂 如

我正在编写一个shell,其他人可以将参数传递给它,例如:

someshell task1 task2 -Daaa=111 -Dbbb=222 task3
在shell中,我可以使用
$@
获取所有参数,即:

task1 task2 -Daaa=111 -Dbbb=222 task3
然后我想从字符串中提取所有以
-D
开头的参数,并生成两个字符串:

-Daaa=111 -Dbbb=222

我不熟悉bash,我现在可以做的是拆分字符串并检查每个项目,然后以某种方式将它们分组。这似乎有点复杂

如果有任何简单的方法可以做到这一点?

一种方法是:

#!/bin/bash

for i in "$@"; do
    [ ${i:0:2} = -D ] && ar1+=( $i ) || ar2+=( $i )
done

echo "string1: ${ar1[@]}"
echo "string2: ${ar2[@]}"
输出

$ bash myarg.sh task1 task2 -Daaa=111 -Dbbb=222 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3
$ bash myarg.sh task1 task2 -Daaa=111 -Dbbb=222 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3
另一种选择:

for i in "$@"; do
    [[ $i = -D* ]] && ar1+=( $i ) || ar2+=( $i )
done
完整示例:

#!/bin/bash

for i in "$@"; do
    [ ${i:0:2} = -D ] && ar1+=( $i ) || ar2+=( $i )
done

echo "string1: ${ar1[@]}"
echo "string2: ${ar2[@]}"

unset ar1
unset ar2

for i in "$@"; do
    [[ $i = -D* ]] && ar1+=( $i ) || ar2+=( $i )
done

echo "string1: ${ar1[@]}"
echo "string2: ${ar2[@]}"

exit 0
输出

$ bash myarg.sh task1 task2 -Daaa=111 -Dbbb=222 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3
$ bash myarg.sh task1 task2 -Daaa=111 -Dbbb=222 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3

也许这是重复的?@col6y'getopt'不适用于我的情况。我不需要解析更多选项,只想用其他方法拆分
-D
,查看一些处理命令行参数的有用方法。