如何将文件的每一行作为选项传递给命令?

如何将文件的每一行作为选项传递给命令?

我想编写一个脚本来读取文件并将每一行作为选项(或“选项参数”)传递给命令,如下所示:

command -o "1st line" -o "2nd line" ... -o "last line" args

做到这一点最简单的方法是什么?

答案1

# step 1, read the lines of the file into a shell array
mapfile -t lines < filename

# build up the command
cmd_ary=( command_name )
for elem in "${lines[@]}"; do
    cmd_ary+=( -o "$elem" )
done
cmd_ary+=( other args here )

# invoke the command
"${cmd_ary[@]}"

答案2

这是一种可能性:

$ cat tmp
1st line
2nd line
3rd line
4th line
$ command $(sed 's|.*|-o "&"|' tmp | tr '\n' ' ')

正如 Glennjackman 在评论中指出的那样,可以通过用 eval 包装来避免分词,尽管安全影响这样做应该受到赞赏:

$ eval "command $(sed 's|.*|-o "&"|' tmp | tr '\n' ' ')"

编辑:sed将我关于使用组装参数的建议与 Glenn jackman 的mapfile/readarray方法相结合,给出以下简洁的形式:

$ mapfile -t args < <(sed 's|.*|-o\n&|' tmp) && command "${args[@]}"

作为一个简单的演示,请考虑上述tmp文件、命令grep和文件text

$ cat text
some text 1st line and
a 2nd nonmatching line
some more text 3rd line end
$ mapfile -t args < <(sed 's|.*|-e\n&|' tmp) && grep "${args[@]}" text
some text 1st line and
some more text 3rd line end
$ printf "%s\n" "${args[@]}"
-e
1st line
-e
2nd line
-e
3rd line
-e
4th line

相关内容