I'm unable to properly handle * character in FOR loop. Bash seems to interpret it as files in current directory instead of * character.
I'm reading a file.txt that contains random words on each line. Some of the lines contain * characters and I want it being interpreted as string instead of list of files in current directory. Say file content looks like this:
cat
house
tree
****
door
book
train
aaaa
a aaa aaa
asdf
Code then reads through each line of the file, stitch new line to variable $linesToInsert together with newline character (\n) and previous content of the variable. This happens for $thisMany times, then whole built up variable is passed to insertDocument() function. This function then adds additional text around each line (stt $eachLine end) of previously built variable $linesToInsert. Issue is with for loop in this function. I can't make bash not interpret it as string of ***** characters, instead it lists files in current directory.
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"
Output should be something like this:
{ cat } { house } { tree } { **** } { door } { book } { train } { aaaa } { a aaa aaa } { asdf }
But I'm getting something like this:
{ cat } { house } { tree } { file1.txt } { file2.txt } { file3.txt } { file4.txt } { file1.txt } { door } { book } { train } { aaaa } { a aaa aaa } { asdf }
Could you please help me make bash properly escape * character in FOR loop?