0

I have to write a Shell script to split the names.txt file into two files male_nominee.txt and female_nominee.txt based on gender.

If file male_nominee.txt or female_nominee.txt already exists, then append the content otherwise we have to make the files. names.txt has text like this:

23|Arjun|Male
24|Akshara|Female
17|Aman|Male
19|Simran|Female

I wrote the following script but something is not right:

#!/bin/bash -x
if [ -f male_nominee.txt ] 
then
     grep -n "Male" names.txt > male_nominee.txt
else
     mkdir -p male_nominee.txt
     grep -n "Male" names.txt > male_nominee.txt
fi
if [ -f female_nominee.txt ]
then 
    grep -n "Female" names.txt > female_nominee.txt
else
    mkdir -p female_nominee.txt
    grep -n "Female" names.txt > female_nominee.txt
fi
schwifty
  • 145
  • 1
  • 12
  • 3
    Making directories means you can't create files with the same name; that is unambiguously wrong. The `>>` operator will append to an existing file and create a non-existing one. That means you can use two `grep` commands (only) to do the job. – Jonathan Leffler Feb 28 '21 at 14:02
  • 3
    Also, you probably don't want `grep -n` but just `grep`. The `-n` would add linenumbers in the format `123:...` that were not there in the original file. And you also should change `"Male"`/`"Female"` to `'|Male$'`/`'|Female$'` to avoid false positives. – Socowi Feb 28 '21 at 14:04
  • @JonathanLeffler so if I write >> it will check for both conditions i.e it will append to existing file or create and then write if it doesn't exist?? – schwifty Feb 28 '21 at 14:05
  • @Socowi thanks for the tip..but won't the search be case sensitive. I am a beginner , so I am sorry if I missed something. Will Male and male be considered same..? – schwifty Feb 28 '21 at 14:06
  • 1
    Both `>>` and `>` will create the file if it doesn't exist. The difference is, if the file exists, then `>>` appends to the file while `>` overwrites the file. – Socowi Feb 28 '21 at 14:08
  • @Socowi oh. Ok got it .Thanks. – schwifty Feb 28 '21 at 14:10
  • @Socowi , thanks I got it to work. Thanks for your help and patience. – schwifty Feb 28 '21 at 14:13

1 Answers1

3

I'd use awk:

awk -F'[|]' '$3 == "Male" { print >> "male_nominee.txt"}
             $3 == "Female" { print >> "female_nominee.txt" }' names.txt

Tell it that pipe is the column delimiter, and depending on the value of the third column, append the current line to the appropriate file (Just like in shell, >> redirection in awk will create the file if it doesn't already exist, and append to existing ones.)

Shawn
  • 47,241
  • 3
  • 26
  • 60