Wednesday, March 16, 2022

[SOLVED] How to store two strings which includes spaces separated by a comma into two separate files in Bash

Issue

second time posting here. I apologize if I make any mistakes in my formatting. I have a file that contains a US State and its respective capital city next to it separated by a comma.

Alabama,Montgomery
Alaska,Juneau
Arizona,Phoenix
Arkansas,Little Rock
California,Sacramento
Colorado,Denver

I am trying to separate the state and city into two separate files and have managed to come up with this,

for line in $(cat file);do
    capital=$(echo $line | cut -d , -f2)
    state=$(echo $line | cut -d , -f1)
    echo $capital >> capitals
    echo $state >> states
done

The problem with this code is that even though I've set the cut delimiter to a comma, the program seems to have space still as a delimiter for cities that contains a space (ex. Little Rock).

With the program I have above, my capitals file contains,

Montgomery
Juneau
Phoenix
Little
Rock
Sacramento
Denver

Notice how Little Rock is in two separate lines and not in the same line. How can I modify my program to have it in the same line? I've tried setting IFS to a comma, but when I do, my capitals file also contains the states.

Alabama
Montgomery
Alaska
Juneau
Arizona
Phoenix
Arkansas
Little Rock
California
Sacramento
Colorado
Denver

Solution

No need to create six child processes for each single line of the input. If the input file gets really large, this will cost a lot of wall clock time. I would do

cut -d , -f2 file > capitals
cut -d , -f1 file > states


Answered By - user1934428
Answer Checked By - Candace Johnson (WPSolving Volunteer)