如何通过参数从.dat文件中获取特定值?

时间:2020-03-24 15:58:34

标签: linux bash

所以,我有一个.dat文件,其中包含一个人的ID,姓名,姓氏,他/她居住的地方... 示例:

0 Alex Brooks Conway 312苏格兰

我需要做一个标志-search,它将带有额外的参数-name -surname,并且只会打印(回显)那些符合条件的人。

例如:
-search -name "Alex" -surname "Brooks"
它将打印出所有与这些标志匹配的人。

我有点迷失了,因为我可以使用awk或grep来做到这一点,但是我不确定哪个更好,以及如何做到这一点

1 个答案:

答案 0 :(得分:0)

这是一个bash脚本,可以执行您想要的操作。在此示例中,的名称为myscript

#!/usr/bin/env bash

##: Initialize the variables
name=
file=
surname=

##: If there are no options/arguments given
[[ $1 ]] || { echo "Give me something!" >&2
  printf '%s\n' "Usage: -s|--surname -n|--name -f|--file" >&2
  exit 1
}

##: loop through the options/arguments

while (($#)); do
  case $1 in
    -n|--name)
      shift
      name=$1
      ;;
    -s|--surname)
      shift
      surname=$1
      ;;
    -f|--file)
      shift
      file=$1;;
    *)
      printf 'Illegal option! %s\n' "$1"  >&2
      printf '%s\n' "Usage: -s|--surname -n|--name -f|--file" >&2
      exit 1;;
  esac
  shift
done

##: If no file what given
if [[ -z $file  ]]; then
  echo "No file given!" >&2
  exit 1
fi

##: Loop through the file line-by-line and check for a match
##: You should be using awk here but I'll leave that to the awk masters :-)

while read -ra line; do
  if [[ ${line[@]} == *" $name $surname "* ]]; then
    if [[ $name == ${line[1]} && $surname == ${line[2]} ]]; then
      printf '%s\n' "${line[*]}"
      exit 0
    fi
  else
     printf '%s %s was not found!\n' >&2 "$name" "$surname"
     exit 1
  fi
done < "$file"

使用方法

./myscript -n Alex -s Brooks -f file.dat

或使用长选项

./myscript --name Alex --surname Brooks --file file.dat
  • 需要更多的测试和错误检查,例如,如果给定的文件不是真正的文件而是目录,等等。