Saturday, December 2, 2023
rated 0 times [  0] [ 0]  / answers: 1 / hits: 1720  / 1 Year ago, sat, december 17, 2022, 9:00:26

I'm doing a project in which I have to parse a csv file (indian liver patient dataset) and I'm trying to change the position of one column. The second to last must be the last column. I'm following these approach but I don't know if It is the right one:

while IFS="," read -r col1 col2 col9 col8 col


echo "$col1, $col2, $col9, $col8"

done < <(cut -d "," --fields=1,2,9,8 csvfile)

Also I need to separate between "Male" and "female" (col2), and just show those values where col9 = 3. The desire output is:

38,Female,3, 5.6
38,Female,3, 5.6
32,Female,3, 6

and so on

72,Male,3, 7.4
60,Male,3, 6.3
33,Male,3, 5.4

and so on

How can I do that without using grep or akw?

More From » command-line


I agree with Muru not allowing the tools best suited is not optimal, probably has its purpose, though. I Don't think it's possible to do this in one loop, at least not without sorting the file first or dropping the header. With an associative array, it's possible to simulate "group by" where the key becomes Female or Male, and its fields are "serialized" as value. In the first loop _ is used to skip fields, and the second for loop iterates through the keys and formats the output.


declare -A A=()
declare -A B=([Male]=Men [Female]=Women)

while IFS=, read -r a b _ _ _ _ _ c d _ ; do
[[ $d = 3 ]] &&
A[$b]+=" $a $b $d $c"
done < file.csv

for e in ${!A[@]}; do
printf %s%sn "$nl" ${B[$e]}
printf '%s, %s, %s, %s
' ${A[$e]}; nl=$'

[#1112] Monday, December 19, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 352
Total Questions: 124
Total Answers: 95

Location: Grenada
Member since Tue, Oct 12, 2021
2 Years ago
ciousuntru questions
Thu, Apr 7, 22, 06:32, 2 Years ago
Tue, Jan 24, 23, 02:14, 11 Months ago
Sat, Dec 18, 21, 21:37, 2 Years ago
Mon, May 30, 22, 05:42, 2 Years ago