Issue
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
Solution
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.)
Answered By - Shawn Answer Checked By - Dawn Plyler (WPSolving Volunteer)