如何正确处理FOR循环中的*(星号)?

时间:2019-01-18 00:24:39

标签: bash

我无法正确处理FOR循环中的*字符。 Bash似乎将其解释为当前目录中的文件,而不是*字符。

我正在读取file.txt,其中每行包含随机单词。有些行包含*字符,我希望将其解释为字符串,而不是当前目录中的文件列表。说文件内容如下:

cat
house
tree
****
door
book
train
aaaa
a aaa aaa
asdf
然后

代码读取文件的每一行,将新行与换行符(\ n)和变量的先前内容一起缝到变量$ linesToInsert。这种情况发生了$ thisMany次,然后将整个构建变量传递给insertDocument()函数。然后,此函数在先前构建的变量$ linesToInsert的每行(stt $ eachLine结尾)周围添加其他文本。此函数中的for循环存在问题。我不能让bash不能将其解释为*****字符的字符串,而是会列出当前目录中的文件。

thisMany=5


insertDocument() {
        documentToInsert=
        IFS=$'\n'
        for eachLine in $1; do
                documentToInsert="$documentToInsert"'{ '"$eachLine"' } '
        done
        echo "$documentToInsert"
}

linesToInsert=

while read i
do
        linesToInsert="${linesToInsert}"$'\n'"${i}";
        cntr=$((cntr+1))

        if [ $cntr -eq $thisMany ]; then

                insertDocument "$linesToInsert"
                cntr=0
                linesToInsert=
        fi
done <file.txt

insertDocument "$linesToInsert"

输出应如下所示:

{ cat } { house } { tree } { **** } { door } { book } { train } { aaaa } { a aaa aaa } { asdf }

但是我得到这样的东西:

{ cat } { house } { tree } { file1.txt } { file2.txt } { file3.txt } { file4.txt } { file1.txt } { door } { book } { train } { aaaa } { a aaa aaa } { asdf }

您能帮我让bash正确地逃避FOR循环中的*字符吗?

1 个答案:

答案 0 :(得分:0)

为防止星号扩展,可以在调用insertDocument之前添加以下行:

set -f

也就是说:

set -f
insertDocument "$linesToInsert"