1
eid|location|desg|status
001|india|hr|active
002|delhi|marketing|inactive
003|hyderabad|sales|active
004|Bangalore|admin|inactive

The data is in the above format, delimiter is '|' Prompt should ask for the eid and display the status as active or inactive.

please enter eid: 001
status is : active
  • 5
    What have you tried so far? This seems like a reasonably straightforward job with awk – Eric Renouf Apr 19 '17 at 12:11
  • @Eric ... or with sed or with grep and cut or with ... – Philippos Apr 19 '17 at 12:36
  • 1
    This isn't a free script writing service. We're here to help you do your work, not do it for you. Try doing this and ask a question here if a specific part of it is giving you trouble. – terdon Apr 19 '17 at 12:48
  • what if i want to search the eid present in for multiple files – vijay raju Apr 20 '17 at 12:54
3

You could use read and sed

read -p "enter an eid: "; sed -n "/$REPLY/ s/.*|\(.*\)/status: \1/p" file

Notes

  • /$REPLY/ find a line with the user input
  • -n only print the lines we ask for
  • s/old/new replace old with new
  • |\(.*\) save any characters after the last | to reference later with \1
  • p print the modified line

To query the newest file:

#!/bin/bash
for f in *; do
  if [[ "$f" -nt "$newest" ]]; then
    "$f"="$newest"
  fi
done
read -p "enter an eid: "
sed -n "/$REPLY/ s/.*|\(.*\)/status: \1/p" "$newest"

Credit to @terdon for finding me this page - because we know ls -t | head -n 1 is not OK

  • what if i want to search multiple files – vijay raju Apr 20 '17 at 12:54
  • Thank you for your answer it really helped me. What if i want to search multiple files in the same directory based on file created timestamp, please help. – vijay raju Apr 20 '17 at 13:07
  • sed will take multiple file arguments (you can put * to search all files in the current working directory, for example). But I'm not sure I understand exactly what you mean by timestamp - you want to look in the 5 most recent files or something like that? – Zanna Apr 20 '17 at 13:12
  • timestamp means like log files created continuously, it should search the latest file created. – vijay raju Apr 20 '17 at 13:35
  • @vijayraju ok, I've edited my answer :) – Zanna Apr 20 '17 at 14:17
3

This does the parsing in sh:

printf 'Enter eid: ' >&2
read query

while IFS="|" read eid location desg status; do
   if [ "$eid" = "$query" ]; then
      printf 'Status is "%s"\n' "$status"
      break
   fi
done <data.in

This is assuming that your data file is called data.in.

Not the answer you're looking for? Browse other questions tagged or ask your own question.