I have a csv file that looks like this
Name,Food,Sport
James,Curry,Gym
Darren,Pizza,Football
Jim,Fish,Hockey
James,Sushi,Tennis
My code looks like this
IFS=","
sed 1d $file_name | while read Name Food Sport
do
mkdir -p $Name
#echo "=================="
#echo "Name: $Name"
done <$file_name
I'm trying to make it so when the directory is created based on the $name column
, it will add something to one of the duplicate names like James_1 or JamesD rather than it only creating a directory for the first James and not the second.
Welcome to the forums.
If you are not expecting the directories to already be there (eg running the script multiple times against the same input file), you could test for the existence and increment a counter.
IFS=","
file_name=infile
sed 1d $file_name | while read Name Food Sport
do
count=0
dirname=$Name
while [ -d "$dirname" ]
do
((count++))
dirname="${Name}_$count"
done
mkdir -p "$dirname"
#echo "=================="
#echo "Name: $Name"
done
1 Like
Appreciate it bro that's perfect, made the counter= 1 from the start so now James looks like James then James 2 rather than 1 just to make it look a little better
Two more suggestions:
- Set IFS only for the read command (unset for other commands)
- Use a builtin to omit the first line (and the while loop runs in the main shell, not forced into a sub shell by a pipe)
sep=","
{
read header
while IFS=$sep read Name Food Sport
do
...
done
} <$file_name