Using shell script I want to read a word from text file and return next column word.
For eg, my input file will be like
AGE1 PERSON1
AGE2 PERSON2
AGE3 PERSON3
AGE4 PERSON4
I have variable in Sh file having PERSON’s name.
I want read input text file and get value of person’s age.
Please help, i’m beginner in Shell Scripting
Building upon shellter‘s comment:
I’ll try to explain everything. First, I assume somethings (but you can change them on your script):
people_file.txt.$person_name.$age.Firstly, because we need to use commands to generate the value of the
$agevariable, we must use$(and)to run a command (or a series of commands), and replace itself with the text it captures from executing the command (or commands).We first need to find the line which contains the person’s name. For that we use grep:
grep regex file. Grep will searchfileline by line until it finds a line that matches the regular expressionregex. In our case we can simply search for the person’s name directly (assuming it doesn’t contain special characters, like the period or an asterisk). Note that we must place the variable between double quotes, otherwise a person’s name that has a space in it might be split in the command line so that its first name is used as the regular expression and the surname as the file. If you want to search in a case insensitive manner (like for example: John will find a line with JOHN or john), you can use the-iflag:grep -i regex file. The selected lines will be printed by grep into its output, but we will pump those lines into the input of the next command with the pipe operator|.Finally, we have a line (or many lines) with the results. Now we must extract the age. The cut command will split each line it reads from the input into fields, and only print the fields you ask it to. In this case, we ask for the first field with the
-f1option. Also, we specify that the space character is to be used as the delimeter (ie. the character that separates the fields) with the-d1command.If you have more than one line with the same person’s name, we need to pipe the output of grep into a head command, so that we can have only the number of lines we want. We can tell head how many lines we want with the
-n Noption. So if you only want the first match:Hope this helps a little =)