gpt4 book ai didi

Bash 列表理解或映射

转载 作者:行者123 更新时间:2023-11-29 09:38:56 25 4
gpt4 key购买 nike

假设我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com