0

I would like to export a CSV bookmarks file as

Physics,physics.stackexchange.com Stack Overflow,stackoverflow.com Unix & Linux,unix.stackexchange.com 

into two Bash arrays. Each array would contain one column of the file. The first array would be

"Physics" "Stack Overflow" "Unix & Linux" 

I have troubles to deals with the blank spaces. I tried to use cut like so

declare names=($(cut -d ',' -f1 ~/bookmarks.csv)) 

which generates an array wherein all the words are separated. As an example, echo ${names[1]} returns

Stack 

and not

Stack Overflow 

    1 Answer 1

    0

    Stack Overflow has a space so it's being treated as two different variables when assigned to the array. In BASH and even other shells like KSH, etc, variable names cannot have spaces in them so a variable like Stack Overflow wouldn't work even if it were surrounded with single or double quotes.

    You can see this with the following commands:

    export Stack Overflow=name echo $Stack Overflow 

    The output will be Overflow as the argument for echo is, in effect, $Stack, which hasn't been declared or assigned a value, and the word Overflow.

    echo $Overflow 

    That will output name as the export command assigned that value to the variable Stack with Overflow=name.

    If you try either of these:

    export "Stack Overflow'=name export 'Stack Overflow'=name 

    You'll get the error -bash: export: Stack Overflow=name': not a valid identifier or -bash: export: Stack Overflow=name': not a valid identifier.

    One thing that you can do instead is to place underscores between the two strings:

    export Stack_Overlow=name 

    That way, echo $Stack_Overflow will output name. That's going to require you to do more work because what you have in the CSV file contains spaces.

    2
    • Thanks for the detailed explanation. Here the name of the array is names which does not contain any blank space. So I if understand well, each array element is in fact an independent variable. A solution would be to initialise an array with n elements (n being the number or rows) and to fill it up with the strings with a for loop?
      – user382051
      CommentedMar 25, 2020 at 16:38
    • @Loïc The value that's assigned to variable is name. The value of the variable can contain spaces but the name of the variable itself cannot contain spaces. You are correct in that each element in the array is an independent variable. With that being said, your proposed solution wouldn't work because it doesn't matter what method you use to assign variables to an array, you can't have variable names with spaces in them and that's why you are running into this issue.CommentedMar 25, 2020 at 16:51

    You must log in to answer this question.