2

I have a below file which containing some data

name:Mark
age:23
salary:100

I want to read only name, age and assign to a variable in shell script

How I can achieve this thing

I am able to real all file data by using below script not a particular data

#!/bin/bash

file="/home/to/person.txt" 

val=$(cat "$file")

echo $val  

please suggest.

4 Answers 4

1

Rather than running multiple greps or bash loops, you could just run a single read that reads the output of a single invocation of awk:

read age salary name <<< $(awk -F: '/^age/{a=$2} /^salary/{s=$2} /^name/{n=$2} END{print a,s,n}' file)

Results

echo $age
23
echo $salary
100
echo $name
Mark

If the awk script sees an age, it sets a to the age. If it sees a salary , it sets s to the salary. If it sees a name, it sets n to the name. At the end of the input file, it outputs what it has seen for the read command to read.

Sign up to request clarification or add additional context in comments.

Comments

1

Using grep : \K is part of perl regex. It acts as assertion and checks if text supplied left to it is present or not. IF present prints as per regex ignoring the text left to it.

name=$(grep -oP 'name:\K.*' person.txt)
age=$(grep -oP 'age:\K.*' person.txt)
salary=$(grep -oP 'salary:\K.*' person.txt)

Or using awk one liner ,this may break if the line containing extra : .

declare $(awk '{sub(/:/,"=")}1' person.txt )

Will result in following result:

sh-4.1$ echo $name
Mark
sh-4.1$ echo $age
23
sh-4.1$ echo $salary
100

1 Comment

What does K do in name:\K.*
0

You could try this

if your data is in a file: data.txt

name:vijay
age:23
salary:100

then you could use a script like this

#!/bin/bash

# read will read a line until it hits a record separator i.e. newline, at which
# point it will return true, and store the line in variable $REPLY
while read 
do
    if [[ $REPLY =~ ^name:.* || $REPLY =~ ^age:.* ]]
    then
        eval ${REPLY%:*}=${REPLY#*:} # strip  suffix and prefix 
    fi
done < data.txt # read data.txt from STDIN into the while loop

echo $name
echo $age

output

vijay
23

Comments

0

well if you can store data in json or other similar formate it will be very easy to access complex data data.json

{
"name":"vijay",
"salary":"100",
"age": 23
}

then you can use jq to parse json and get data easily

jq -r '.name' data.json
vijay

1 Comment

Huh? The question didn't even mention JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.