Bash

如何將文件的每一行作為選項傳遞給命令?

  • November 8, 2017

我想編寫一個腳本來讀取文件並將每一行作為選項(或“選項參數”)傳遞給命令,如下所示:

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

最簡單的方法是什麼?

這是一種可能性:

$ 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' ' ')"

**編輯:**將我使用sedto assemble arguments 的建議與 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
# 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[@]}"

引用自:https://unix.stackexchange.com/questions/403398