bash如何声明和迭代值对(其中值可能包含空格)(二维数组) [英] bash How to declare and iterate over pairs of values where values may contain spaces (two dimensional array)
问题描述
例如,我有成对的目录.这些对包含空格(和/或其他不便之处,例如加号或特殊字符.ext4容易支持的说法.)
I have pairs of, for example, directories. The pairs contain spaces (and/or other inconveniences like extra periods or special chars. Anything ext4 easily supports let say.)
'/foo/dolor sit/amet.elit' '/bar/accumsan/luctus massa.nec'
'/baz/sagittis. Fusce/vitae.dolor' '/bam/Nunc aliquetjusto.metus'
我想编写一个bash脚本,其中这些对是硬编码/常量的.
I want to write a bash script where these pairs are hard-coded/constants.
我非常希望在定界符中声明这些字符串,或者不需要对任意字符串进行预处理(例如,如果可能的话,我不想在所有文字空白上添加转义符)
I would highly prefer declaring the strings within a delimiter or such that does not need the arbitrary string to be preprocessed (eg I don't want to add escapes on all literal whitespaces if possible)
对于声明的字符串对,我希望进入一个循环,其中两个字符串在一次迭代中都可以作为单独的变量使用,例如 $ LEFT
和 $ RIGHT
.
With declared pairs of strings, I wish to enter a loop where both the strings are available in one iteration as separate variables, e.g. $LEFT
and $RIGHT
.
就像使用简单的文件操作一样,例如复制,移动,链接,比较.
Likely uses being simple file operations like copy, move, link, diff.
注释:
- 数组的高度"应允许很多对.
- 如果声明和迭代可以支持大于2的2D数组,请注意如何扩展到所需的范围.
- 如果bash具有特定于数组"的数据类型,则对问题/答案不是必不可少的.任何可迭代的二维声明和迭代就足够了.
推荐答案
一种愚蠢而简单的方法,如果仍然要对数据进行硬编码,则可以将数据作为Shell函数的参数进行硬编码.
A stupid-simple approach, If you're going to hard code the data anyway, you can hard code the data as parameters to shell functions.
#!/usr/bin/env bash
do_for_pair() {
echo $1
echo $2
}
do_for_pair "/foo/dolor sit/amet.elit" "/bar/accumsan/luctus massa.nec"
do_for_pair "/baz/sagittis. Fusce/vitae.dolor" "/bam/Nunc aliquetjusto.metus"
这篇关于bash如何声明和迭代值对(其中值可能包含空格)(二维数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!