3

I have a text file with data in it which is set up like a table, but separated with commas, eg:

Name, Age, FavColor, Address

Bob, 18, blue, 1 Smith Street

Julie, 17, yellow, 4 John Street

Firstly I have tried using a for loop, and placing each 'column' with all its values into a separate array.

eg/ 'nameArray' would contain bob, julie.

Here is the code from my actual script, there is 12 columns hence why c should not be greater than 12.

declare -A Array

for((c = 1; c <= 12; c++))
{
    for((i = 1; i <= $total_lines; i++))
    {
        record=$(cat $FILE | awk -F "," 'NR=='$i'{print $'$c';exit}'| tr -d ,)
        Array[$c,$i]=$record

    }
}

From here I then use the 'printf' function to format each array and print them as columns. The issue with this is that I have more than 3 arrays, in my actual code they're all in the same 'printf' line. Which I don't like and I know it is a silly way to do it.

for ((i = 1; i <= $total_lines; i++))
{
    printf "%0s %-10s %-10s...etc \n" "${Array[1,$i]}" "${Array[2,$i]}" "${Array[3,$i]}" ...etc
}

This does however give me the desired output, see image below:

enter image description here

I would like to figure out how to do this another way that doesn't require a massive print statement. Also the first time I call the for loop I get an error with 'awk'.

Any advice would be appreciated, I have looked through multiple threads and posts to try and find a suitable solution but haven't found something that would be useful.

1 Answer 1

7

Try the column command like

column -t -s','

This is what I can get quickly. See the man page for details.

Sign up to request clarification or add additional context in comments.

4 Comments

I can't believe I did all that for the same output haha. Only issue is I get column line too long.
Recalled this from long long ago, not sure about the details, maybe the manual might be able to help you.
Bugs: "Input lines are limited to LINE_MAX (2048) bytes in length." Could be the issue.
When I did this, it converted all of my UTF-8 characters into codepoints.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.