0

I'm trying to read a bash array file by file but for files with spaces in them, it comes out as two separate files. How would I solve this? file names:

file A
fileB
file_C

the output Im getting is like this

File
A
FileB
File_C

What Im trying to do is to get File A on one line I know I can read the array at once but for now we need to do it with a for loop since we're gonna be doing operations to it later in the loop.

for i in "${array[@]}"; do
    echo "$i"
done
  • If you escape the space in File A there's no issue, e.g. `array=(File A FileB File_C) && echo "${array[0]}"` prints "File" (bad), but `array=(File\ A FileB File_C) && echo "${array[0]}"` prints "File A" (good). Ideally you would use `for f in File*; do echo "$f"; done` to avoid the issue, but I'm guessing your actual files don't all begin with the word "File" – jared_mamrot Feb 05 '21 at 05:17
  • Oh, and you can also use single quotes, e.g. `array=('File A.txt' 'FileB.txt' 'File_C.txt') && echo "${array[0]}"` prints "File A.txt" (good) – jared_mamrot Feb 05 '21 at 05:25
  • So I would basically look for spaces in the array and add "\" to file name where they begin. Oh putting everything in single quotes sounds much easier and faster lol, thanks – user1922979 Feb 05 '21 at 05:25
  • No problem, and I believe you can also turn off word splitting by setting IFS (see e.g. https://stackoverflow.com/a/26554333/12957340) - in fact this is basically a duplicate of that question and it will probably get closed. – jared_mamrot Feb 05 '21 at 05:43
  • 1
    Does this answer your question? [Bash arbitrary glob pattern (with spaces) in for loop](https://stackoverflow.com/questions/26554133/bash-arbitrary-glob-pattern-with-spaces-in-for-loop) – jared_mamrot Feb 05 '21 at 05:43
  • @jared_mamrot Im supposed to do it with just "basic tools and loops" so I dont think I can use that. Im still trying to single quote method or the slash to see if it works – user1922979 Feb 05 '21 at 06:07
  • Are you writing the filenames literally in the script, or reading/expanding them from somewhere? If you're including the names literally in the script, then quoting/escaping will work. If you're reading them from somewhere, do *not* try to add quotes or escapes; instead, read them using a method that doesn't split on spaces. See [BashFAQ #20: How can I find and safely handle file names containing newlines, spaces or both?](http://mywiki.wooledge.org/BashFAQ/020) – Gordon Davisson Feb 05 '21 at 06:11
  • @GordonDavisson Yeah I just realized that lol I guess I'll just use one of those methods then, Thanks. – user1922979 Feb 05 '21 at 06:43
  • The problem may very well be in the way you declare, or assign values to the array, rather than the way you iterate the array. Could you show us how you are setting up the array? – Andrew Vickers Feb 05 '21 at 19:17

0 Answers0