截断星号获得的变量时抑制外壳扩展

时间:2018-06-21 19:52:46

标签: bash shell variable-expansion

我的文件夹中有以下文件:

function image($path, $options = array())
{
    $defaults = array(
        'class' => null
    );
    $options += $defaults;

    $options['class'] = 'lazy ' . $options['class'];

    $originalTemplate = $this->tags['image'];
    $this->tags['image'] = '<img data-src="%s" %s/>';

    $imageHtml = parent::image($path, $options);

    $this->tags['image'] = $originalTemplate;

    return $imageHtml;
}

我使用以下脚本为所有116种类型获取所需的文件名前缀:

roi_1_Precentral_L/
roi_1_Precentral_L_both.fig
roi_1_Precentral_L_left.fig
roi_1_Precentral_L_right.fig
roi_1_Precentral_L_slice.fig
roi_2_Precentral_R/
roi_2_Precentral_R_both.fig
...
roi_116_Vermis_10/
roi_116_Vermis_10_both.fig
roi_116_Vermis_10_left.fig
roi_116_Vermis_10_right.fig
roi_116_Vermis_10_slice.fig

所需iroi = 1的输出

for iroi in `seq 1 116`;
do
    d=roi_${iroi}_*/
    d2=${d:0:-1}         # <-- THIS LINE IS IMPORTANT
    echo $d2
done;

实际输出

$ roi_1_Precentral_L

如何避免在强调的代码行中进行shell扩展以产生所需的输出?

2 个答案:

答案 0 :(得分:2)

如果您分配给数组,则将在第一行扩展全局,而不是像原始代码那样在<?php if(isset($_POST['parameters'])) { echo "Hello"; $value = $_POST['parameters']; // I can get the other 2 parameters like this $company = htmlspecialchars(trim($value['booking'])); $partner = htmlspecialchars(trim($value['partner'])); // not sure how to get the uploaded file information } ?> 以后扩展。

echo

如果您希望有多个目录,d=( "roi_${iroi}_"*/ ) d2=${d:0:-1} # Note that this only works with new bash. ${d%/} would be better. echo "$d2" 将展开到完整列表,并且从每个目录中删除结尾的"${d[@]%/}"

/

关于避免不必要的扩展-请注意,在上文中,扩展都用双引号括起来,除了简单(字符串,而不是数组)赋值右侧的扩展。 (常规赋值隐式禁止字符串拆分和glob扩展-尽管即使在那时也没有引号也无害!这是为什么d=( "roi_${iroi}_"*/ ) printf '%s\n' "${d[@]%/}" 从glob表达式本身而不是从glob表达式中删除${d:0:-1}的原因结果)。

答案 1 :(得分:0)

回答问题

如果需要,您可以引用以避免*$d的扩展...

d=roi_${iroi}_*/
d2="${d:0:-1}"
echo $d2

...但是您可以直接写...

d2="roi_${iroi}_*"
echo $d2

...,输出仍然与您的问题相同。

预期产出的答案

您可以在数组中进行扩展并选择第一个数组条目,然后从该条目中删除/

for iroi in {1..116}; do
    d=(roi_"$iroi"_*/)
    d2="${d[0]:0:-1}"
    echo "$d2"
done

这仅匹配目录,并打印第一个目录,而没有结尾的/