通过连接字符串迭代路径 - 防止通配

时间:2017-04-24 12:58:29

标签: linux shell debian

如何循环/遍历字符串

exclude_args=''
exclude='/var/www/bak/*/* /var/test'
set -- "$exclude"
shift
for path; do
  exclude_args="$exclude_args --exclude '$path'"
done
echo "$exclude_args"

输出

 --exclude '/var/www/bak/*/* /var/test'

如何获得这样的输出

 --exclude '/var/www/bak/*/*' --exclude '/var/test'

2 个答案:

答案 0 :(得分:0)

你正在追寻相当倾斜的道路。利用数组和printf

exclude=( '/var/www/bak/*/*' '/var/test' )
printf -- '--exclude %s ' "${exclude[@]}"
  • exclude=('/var/www/bak/*/*' '/var/test')将所需内容作为数组exclude的元素

  • printf -- '--exclude %s ' "${exclude[@]}"打印前面带有字符串--exclude的数组元素

要在最后添加换行符,请添加echo

printf ...; echo

示例:

$ exclude=( '/var/www/bak/*/*' '/var/test' )

$ printf -- '--exclude %s ' "${exclude[@]}"; echo
--exclude /var/www/bak/*/* --exclude /var/test 

答案 1 :(得分:0)

由于您已将其标记为LinuxShell,我认为您需要POSIX shell解决方案。您可以执行相同的操作,允许使用printf进行正常的单词拆分,正如Heemayl在他的回答中正确建议的那样,但没有数组。首先,如果您的系统允许您使用set -f来阻止路径名扩展,请使用:

#!/bin/sh
set -f
exclude_args=""
exclude='/var/www/bak/*/* /var/test'
printf " --exclude '%s'" $exclude
printf "\n"

如果由于某种原因无法使用set -f,则需要将每个组件用单引号括起来以防止扩展,您可以使用sed强制执行此操作:

#!/bin/sh
exclude_args=''
exclude='/var/www/bak/*/* /var/test'
exclude="$(echo "$exclude" | sed -e "s/[ ]/' '/g" -e "s/\(^.*$\)/'\1'/")"
printf " --exclude %s" $exclude
printf "\n"

注意: $exclude没有引用,因为printf的参数是故意的。

如果您想在exclude_args变量中捕获该输出,(并且您的系统为-v提供printf选项,则只需使用printf -v表单,例如

#!/bin/sh
exclude_args=''
exclude='/var/www/bak/*/* /var/test'
exclude="$(echo "$exclude" | sed -e "s/[ ]/' '/g" -e "s/\(^.*$\)/'\1'/")"
printf -v exclude_args " --exclude %s" $exclude
echo "$exclude_args"

示例使用/输出

$ sh exargs.sh
 --exclude '/var/www/bak/*/*' --exclude '/var/test'

如果那不是您要找的东西,那么我很困惑,请删除所需的任何其他信息。