Reputation: 91
I am trying to read file that contains a single line
cpu=msm8998
I need to grab the value after "=" and assign it to a variable. What's the simplest way to do it ? without using cat if possible
Upvotes: 0
Views: 329
Reputation: 14924
Assuming this text is in a file cpu.txt
:
#! /usr/bin/env bash
CPU_FILE="cpu.txt"
CPU=`awk -F= '{ print $2 }' "$CPU_FILE"`
echo "\$CPU = $CPU"
Using awk
to split on the =
(that's the awk -F=
), output the 2nd field ( { print $2 }
), then store the output of all that into $CPU
with back-tick enclosure (I'm not sure of the proper name for this, if any).
Upvotes: 1
Reputation: 212684
If your input file is just that one line, then you should source it:
$ cat input
cpu=msm8998
$ echo $cpu
$ . input
$ echo $cpu
msm8998
Upvotes: 3
Reputation: 14520
If that's really all that's in the other file, I'd just source it, the example you gave is a valid shell assignment:
$ cat file
pu=msm8998
$ cat using_it
#!/bin/bash
. file
printf '%s\n' "$cpu"
$ ./using_it
msm8998
Upvotes: 0
Reputation: 158280
Use the read
builtin:
IFS== read name value < file
echo "${value}"
read
splits the input into fields delimited by IFS
the shell's internal field separator. In your example the field separator is =
.
Alternatively, just source the file:
source file
echo "${cpu}"
Upvotes: 5
Reputation: 58998
This will do it:
my_var="$(cut -d= -f2 my_file.txt)"
The cut
command basically says to split each line in my_file.txt into fields separated by equals signs, and print only the second field.
Test session:
$ echo cpu=msm8998 > my_file.txt
$ my_var="$(cut -d= -f2 my_file.txt)"
$ echo "$my_var"
msm8998
Upvotes: 1