如何将命令行上的字符串转换为单独的位置参数
How to turn strings on the command line into individual positional parameters
我的主要问题是如何在 Linux 中使用终端命令将命令行上的字符串拆分为参数?
例如
在命令行上:
./my program hello world "10 20 30"
参数设置为:
$1 = 你好
$2 = 世界
$3 = 10 20 30
但我想要:
1 美元 = 你好
$2 = 世界
$3 = 10
4 美元 = 20
5 美元 = 30
如何正确操作?
使用xargs
:
echo "10 20 30" | xargs ./my_program hello world
xargs is a command on Unix and most Unix-like operating systems used
to build and execute command lines from standard input. Commands such as
grep and awk can accept the standard input as a parameter, or argument
by using a pipe. However, others such as cp and echo disregard the
standard input stream and rely solely on the arguments found after the
command. Additionally, under the Linux kernel before version 2.6.23,
and under many other Unix-like systems, arbitrarily long lists of
parameters cannot be passed to a command,[1] so xargs breaks the list
of arguments into sublists small enough to be acceptable.
(source)
您可以使用 set builtin. If you do not double-quote $@
重置位置参数 $@
,shell 将对其进行分词以产生您想要的行为:
$ cat my_program.sh
#! /bin/sh
i=1
for PARAM; do
echo "$i = $PARAM";
i=$(( $i + 1 ));
done
set -- $@
echo "Reset $@ with word-split params"
i=1
for PARAM; do
echo "$i = $PARAM";
i=$(( $i + 1 ));
done
$ sh ./my_program.sh foo bar "baz buz"
1 = foo
2 = bar
3 = baz buz
Reset $@ with word-split params
1 = foo
2 = bar
3 = baz
4 = buz
顺便说一句,您想要这样做有点令人惊讶。许多 shell 程序员对 shell 容易、意外的分词感到沮丧 — 他们在想要保留 "John Smith" 时得到 "John"、"Smith" — 但是这似乎是你的要求。
我的主要问题是如何在 Linux 中使用终端命令将命令行上的字符串拆分为参数? 例如 在命令行上:
./my program hello world "10 20 30"
参数设置为:
$1 = 你好
$2 = 世界
$3 = 10 20 30
但我想要:
1 美元 = 你好
$2 = 世界
$3 = 10
4 美元 = 20
5 美元 = 30
如何正确操作?
使用xargs
:
echo "10 20 30" | xargs ./my_program hello world
xargs is a command on Unix and most Unix-like operating systems used to build and execute command lines from standard input. Commands such as grep and awk can accept the standard input as a parameter, or argument by using a pipe. However, others such as cp and echo disregard the standard input stream and rely solely on the arguments found after the command. Additionally, under the Linux kernel before version 2.6.23, and under many other Unix-like systems, arbitrarily long lists of parameters cannot be passed to a command,[1] so xargs breaks the list of arguments into sublists small enough to be acceptable.
(source)
您可以使用 set builtin. If you do not double-quote $@
重置位置参数 $@
,shell 将对其进行分词以产生您想要的行为:
$ cat my_program.sh
#! /bin/sh
i=1
for PARAM; do
echo "$i = $PARAM";
i=$(( $i + 1 ));
done
set -- $@
echo "Reset $@ with word-split params"
i=1
for PARAM; do
echo "$i = $PARAM";
i=$(( $i + 1 ));
done
$ sh ./my_program.sh foo bar "baz buz"
1 = foo
2 = bar
3 = baz buz
Reset $@ with word-split params
1 = foo
2 = bar
3 = baz
4 = buz
顺便说一句,您想要这样做有点令人惊讶。许多 shell 程序员对 shell 容易、意外的分词感到沮丧 — 他们在想要保留 "John Smith" 时得到 "John"、"Smith" — 但是这似乎是你的要求。