hi all!
i have a working that looks like this...
file1
MALE JOHN
MALE ANJO
FEMALE ANNE
MALE JAMES
FEMALE HONEY
FEMALE IZA
what i want to do is insert "M" when the first string is "MALE" and insert "F" when the first string is "FEMALE".
file1
M MALE JOHN
M MALE ANJO
F FEMALE ANNE
M MALE JAMES
F FEMALE HONEY
F FEMALE IZA
i tried awk:
if($1 == "MALE")
{print "M"" "$1" "$2}
else
{print "F"" "$1" "$2}
but is there any other one-liner code that would do the job? output should overwrite the working file. thanks!
Something like this:
awk '{print substr($1,1,1) FS $0}' file
@franklin : actually, it's not the first letter that should be inserted. im sorry if i mislead you, it's just an example. Thanks!
Ok, then you should give a more elaborate example.
Regards
for example: if the first string of a line is "MALE", then insert a string like "AM" before it.
What are you trying to accomplish, can you give an explanation of your real world problem?
Regards
i have this working file that i can't find all the values i needed. so, what i want to do is to put that missing value before the first string of each line.
Assuming you mean the first word of the line:
awk '/^MALE/{print "AM" $0}' file
---------- Post updated at 16:54 ---------- Previous update was at 16:36 ----------
Or maybe you mean something like:
awk '/^MALE/{$0="AM" $0}1' file
Regards
kshji
July 18, 2009, 11:13am
9
Here is example how to make n rules.
#!/bin/sh
file="file1"
cp $file $file.bak
tf=$$.tmp
awk '
# rule and print
/^MALE / { print "M",$0 ; next }
/^FEMALE / { print "F",$0 ; next}
# default
{ print "?",$0 }
' $file > $tf
# overwrite original file
cat $tf > $file
rm -f $tf
Trythis:
echo 'MALE JOHN' | sed 's/^MALE /M MALE /; s/^FEMALE /F FEMALE /;'
Output:
M MALE JOHN
You can add more substitutions as you want.
Just like this "'s/^THIS THING /TT THIS THING /; "
shell:
sed 's/^\([A-Z]\)/\1 \1/'
perl:
perl -ne '{s/^([A-Z])/(($1 eq "M")?"M ":($1 eq "F")?"F ":"O ").$1/e;print;}'