将文件行解析为bash脚本参数

时间:2019-01-16 15:24:08

标签: bash

我有一个文件(commands),其中包含要用每行一个命令执行的命令列表。我需要使用bash脚本(main.sh)解析每一行以保持参数完整,以便可以将它们传递给另一个bash脚本(helper.sh)。

例如:

如果commands包含:

echo -e "hello world\n"
cat path_to/some\ file
...

我需要main.sh才能像bash脚本一样区分每一行中的参数(所需结果):

for line 1:
command: echo
$1: -e
$2: hello world


for line 2:
command: cat
$1: path_to/some file

这样我就可以将它们存储在数组中,并将它们正确地传递到helper.sh

到目前为止,我最终得到的是(当前结果):

for line 1:
command: echo
$1: -e
$2: "hello
$3: world
"

for line 2:
command: cat
$1: path_to/some\
$2: file

1 个答案:

答案 0 :(得分:1)

Python为此提供了一个方便的模块shlex。尝试类似的东西:

$ cat shparse.py
import shlex
import fileinput

for line in fileinput.input():
    parts = shlex.split(line)
    print(f'command: {parts[0]}')
    argument_number = 1
    for argument in parts[1:]:
        print(f'${argument_number}: {argument}')
        argument_number += 1
$ cat commands.txt
echo -e "hello world\n"
cat path_to/some\ file
$ python3 shparse.py <commands.txt
command: echo
$1: -e
$2: hello world\n
command: cat
$1: path_to/some file