Hello all
I have a data base of information that is formatted like so:
JSD4863 XXX-XX-XXXX DOE, JOHN C JR-II BISS CPSC BS INFO TECH 412/779-9445
I need the last four digits of the phone number. However, many lines contain
'garbage data' that I'm not interested in. So i used a 'for loop' to specify
which lines i wanted. The code looks like this:
#!/bin/bash
for linePosition in {11..22}
do
holder=`sed -n "${linePosition}p" $1|awk '{print $12}'`
echo "$holder"
done
This gives me the 11 lines that I want. However, it gives me the full phone
number. I want to ALSO pipe this command to only give me the last 4 digits.
I am not sure how to do this since the fields are delimited by two different
characters. I tried a couple variations of cut, but nothing work.
Please help
BASH itself lets you use multiple characters as the delimiter without the help of sed and awk.
while IFS=" -" read JSD AAA BB CCCC G
do
echo "First col $JSD"
echo "Second col $AAA"
echo "Third col $BB"
echo "Fourth col $CCC"
echo "Fifth and later cols $G"
done < "$1"
It reads the entire file, one line at a time, into the variables listed. It uses IFS to change the shell's default delimiters. It will split on all characters listed in IFS.
Running the code would also give you a better idea what it does.
Running cut to edit individual lines is like making 300 phone calls to say one word apiece. Best to break that habit as early as possible.
You could try this, fields are read into bash array name C starting with index 0 for field 1 (index 11 for field 12):
#!/bin/bash
sed -n "11,22p" $1 | while read -a C
do
front=${C[11]%????} # Front = Everything except last four chars of C[11] (field 12)
holder=${C[11]#$front} # Remove $front from front of C[12] and store in holder
echo "$holder"
done
If all you want is the last four digits of the phone numbers on lines 11 through 22 of your data file and the phone number is the last field on those 12 lines, a couple of simple ways to do that are:
#!/bin/bash
echo "Using awk:"
awk -F- '
NR < 11 {next}
NR > 22 {exit}
{print $NF}' $1
echo "Using sed:"
sed -n '11,22s/.*-//p' $1