Bash 列表理解或映射

标签 bash

假设我在 bash 中有一个字符串 -

NAMES="file1 file2 file3"

如何将它映射到我将用作命令的一部分的以下字符串?

MAPPED="-i file1.txt -i file2.txt -i file3.txt"

为了准确说明我的意思,这里是等效的 python 代码 -

names = "file1 file2 file3"
mapped = ' '.join("-i " + x + ".txt" for x in names.split())

最佳答案

你应该使用数组而不是字符串:

names=(file1 file2 file3)

# Add suffix
names=("${names[@]/%/.txt}")

# Build new array with "-i" elements
for name in "${names[@]}"; do
    mapped+=(-i "$name")
done

# Show result
declare -p mapped

导致此输出:

declare -a mapped=([0]="-i" [1]="file1.txt" [2]="-i" [3]="file2.txt" [4]="-i" [5]="file3.txt")

现在可以在这样的命令中使用:

cmd "${mapped[@]}"

参见 BashFAQ/050关于将命令放入字符串与数组的基本原理。

关于Bash 列表理解或映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56349804/

相关文章:

bash - 如何在变量中获取 bash 命令的输出

bash - 如何在具有标题行的文件上使用 Unix 排序命令?

linux - 脚本中和脚本外的相同命令的结果不同

linux - Bash:在变量内使用单引号

linux - 如何使用 awk 显示文本文件中的某些特定字段?

linux - 选项前有参数时 getopts 不起作用

python - 在命令行应用程序中打印标准输出而不覆盖待处理的用户输入

regex - 隐藏猫提示错误

xmllint - 无法读取特殊字符

用于创建文件夹和移动文件的 linux bash 脚本