gpt4 book ai didi

bash - 如何在 bash 中迭代多行变量?

转载 作者:行者123 更新时间:2023-12-05 07:41:55 25 4
gpt4 key购买 nike

给定

# this is programmatically generated... hard-coded here for this example
commands="\nthing1@this is thing 1!\nthing2@this is thing 2!"

while read -r line; do
cmd=$(printf "$line" | cut -d'@' -f1 | tr -d '\n')
desc=$(printf "$line" | cut -d'@' -f2 | tr -d '\n')

printf ' %-20s %s\n' "$cmd" "$desc"
done <<< "$commands"

我希望能输出

  thing1        this is thing1!
thing2 this is thing2!

相反我得到

  thing1thing2        this is thing1!this is thing2!

我做错了什么?

我想在换行符上读取,这样我就可以在@printf 上相应地cut

最佳答案

#!/bin/bash

input="\nthing1@this is thing 1!\nthing2@this is thing 2!"

# echo replaces '\n's with real new-lines
# readarray -t loads the multiline string into an array
readarray -t array <<< $(echo -e "${input}")

# loop it
for command in "${array[@]}"; do
echo "${command}"
done

关于bash - 如何在 bash 中迭代多行变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44959712/

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