Skip to content
Advertisement

Reading tabular data from a line in bash [closed]

I need to check if the pin that user gives exists and if exists then display their names and surnames… i need it in bash script PS: we’ve got a file with cardpins,name,surname,E/A (accepted or no for other questions) and account balance in this format:

0098876634569080 NIKOLAOU VASILEIOS Ε 25575 
0033872234566751 MAVRAGANIS GEORGIOS Α 12345

i’ve done this

read -p "Insert Pin"
if ! grep $REPLY filename
then
echo "ERROR"
exit 1
else grep $REPLY filename
$V1=grep -c $REPLY filename
head -$v1 filename | :   and then dunno :P 

Advertisement

Answer

As I gather it, this is essentially a question about reading fields from a file. grep isn’t a good tool — it would give you a match if the PIN were found in a different field (ie. balance), or if the value given were only a substring of a PIN (for instance, if the user entered 0 for their PIN). Consider instead:

read -p "Insert Pin"

found=0
while read -r pin name surname has_accepted balance; do
  # unlike grep, look ONLY in pin field, and ONLY for exact match
  if [[ $pin = "$REPLY" ]]; then
    found=1
    echo "Name is $name; surname is $surname; balance is $balance; etc"
    break # don't continue to look after we found a match
  fi
done <filename

if ! (( found )); then
  echo ERROR >&2
  exit 1
fi

See BashFAQ #001 for a long-form discussion of reading data in bash.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement