替换字符串的单引号除以变量的空格

DaW*_*444 1 bash solaris variable read rewrite

我正在编写一个 bash 脚本,我正在通过read这两个字符串读取变量:

log.*.console.log log.*.log
Run Code Online (Sandbox Code Playgroud)

它们被空间隔开。

如何重写脚本中调用的下一个程序的变量的输出将具有这种形式的字符串? 'log.*.console.log' 'log.*.log'

我正在尝试 sed 和 awk 但不知何故没有成功。

整个脚本:

#!/bin/bash
if [ -z "$*" ] ; then
echo "USAGE: ./some text"
exit 1

else

echo "some text"
read varlogname

i=1
for file in $@
do
echo "Doing" $file
GTAR=$(gtar -xvf $file --wildcards --ignore-case --no-anchored "$varlogname")

for file in ${GTAR[*]}
do
mv $file $file"."${i}
i=$((i+1))
done
done
echo "Files extracted."
fi
exit 0
Run Code Online (Sandbox Code Playgroud)

ilk*_*chu 5

我认为您不想给gtar. 在诸如 之类的命令中somecmd 'foo bar' 'files*.log',shell 将处理引号,它们告诉它不要特别处理特殊字符,并传递somecmd参数foo barfiles*.log。Unix 程序不会将命令行作为一个字符串,而是作为多个参数字符串获取,shell 将命令行拆分为字符串。

如果要read在 Bash 中使用多个值,可以使用read -a array, 然后将数组交给命令。

  -a array  assign the words read to sequential indices of the array
            variable ARRAY, starting at zero
Run Code Online (Sandbox Code Playgroud)

IE

read -a filenames
gtar "${filenames[@]}"
Run Code Online (Sandbox Code Playgroud)

索引数组 [@](在引号中)会将数组成员扩展为单独的单词,这正是您想要的。

此外,您有for file in ${GTAR[*]}. 这看起来像是GTAR作为一个数组访问,但它不是一个,您只是将gtar命令的输出作为字符串分配给它。在这种情况下${GTAR[*]}$GTAR. 由于扩展没有被引用,此时字符串会进行分词,默认情况下会在空格上进行分词。但是,在那之后,这些词被当作​​文件名 globs 并扩展为匹配的文件名。

只要您的文件名不包含空格或通配符 ( *?[],这很好。但总的来说,这不是您想要做的。

对于正确的数组,您可能总是想要使用"${array[@]}"而不是[*].

请参阅:分为什么我的 shell 脚本会因空格或其他特殊字符而阻塞?数组