Split line in shell script while reading from file
I have the following script that is supposed to read line by line from a .properties file and then tokenize based on the "=" separator and store the values ββinto two variables and then display them. But I don't understand how to tokenize it and then store it in two different variables and then use it for further purposes.
The post script works fine when reading the file line by line, but I need help implementing the line splitting logic.
"Properties file"
FNAME=John
LNAME=Lock
DOB=01111989
Script
#!/bin/bash
echo "FileReading Starts"
while read line
do
value=$line
echo $value
#Tokenize Logic
property=sample
property_value=sample
echo $property
echo $property_value
done <testprop.properties
echo "Finish"
source to share
Try the following:
#!/bin/bash
while IFS='=' read -r col1 col2
do
echo "$col1"
echo "$col2"
done <testprop.properties
IFS
- input signal separator.
But instead of parsing the file (like fedorqui ), you can directly load the file and access the variables:
source testprop.properties
echo "$FNAME"
From $ LANG=C help source
:
source: source filename [arguments]
Execute commands from a file in the current shell.
Read and execute commands from FILENAME in the current shell. The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.
Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
Last but not least, use more quotes ! See http://mywiki.wooledge.org/Quotes , http://mywiki.wooledge.org/Arguments, and http://wiki.bash-hackers.org/syntax/words .
source to share
IFS
can be used to set field separator values ββto read
Example
while IFS="=" read line val
do
echo $line : $val;
done < inputFile
Gives output as
FNAME : John
LNAME : Lock
DOB : 01111989
Internal variable
$IFS
internal field separator
This variable determines how Bash recognizes fields, or word boundaries, when it interprets character strings.
source to share
using declare (declare -a query = $ (cat "file.sql")) I am calling a file with sql queries like:
current .sql file:
["select filespace_name from Occupancy"]
["select filespace_name, date (backup_end) from filespaces"]
["select node_name from nodes"]
and the script getting all requests in the file content on one line .. instead of executing one at a time.
using run
for Q in "${query[@]}"; do
happy with any siggestion ....
source to share