I'm new to linux and i decided to learn shell scripting. I have created a file data.txt that contains the following text:
12345 Nick Abrams A 10900
67890 George Kennedy I 20000
(text goes on...)
The first field is a card's pin number, the second is the name of the client, third is surname, fourth indicates whether a card is active (or inactive) and the last field is the client's balance. I need to write a script that receives the client's pin from keyboard and if that pin is written in the text file then the script should print the client's name and surname on the screen. I have used grep like this
grep "^$pin" data.txt
But it returns all the details of a client. I only need to print the second and third field and ignore everything else. Is there any parameter to isolate the words i need?
Could you please try following and let me know if this helps you.
cat script.ksh
echo "Please enter your choice:"
read value
awk -v val="$value" '$1==val{print $2,$3}' Input_file
EDIT: Adding a solution with grep
and cut
in a script too here.
cat script.ksh
echo "Please enter your choice:"
read value
grep "$value" Input_file | cut -d" " -f2,3
#!/bin/bash
echo "Enter PIN, please"
read pin
grep "${pin}" pins.txt | awk '{print $2" "$3}'
Input: 12345
Output: Nick Abrams
Or with cut
:
#!/bin/bash
echo "Enter PIN, please"
read pin
grep "${pin}" pins.txt | cut -d' ' -f2,3
Better use sed :
sed -n 's/^'"$pin \([^ ]* [^ ]*\).*"'/\1/p' data.txt
This command match a line that start by $pin
, and write only part that follow regex between \\(
and \\)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.