Split String in shell script while reading from fi

2020-06-16 03:28发布

问题:

I have a following script which should read line by line from a ".properties" file and then tokenize it on base of "=" delimiter and store values into two variables and then display it. But I am not getting understanding of how to tokenize it and then store it in two different variables and then use it for further purposes.

Following script works fine in reading the file line by line but i need help in implementing the logic of splitting the string.

"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"

回答1:

Try this :

#!/bin/bash

while IFS='=' read -r col1 col2
do 
    echo "$col1"
    echo "$col2"
done <testprop.properties

IFS is the Input Filed Separator.

But instead of parsing the file (like fedorqui said), you can source the file and accessing the variables directly:

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.



回答2:

The 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.


回答3:

I wander if it is possible to separate in the answer file itself (sending sql queries)

current file.sql have select ....... select ....... select .......

and script getting in file like declaration and working fine if file have only one query

declare -a query=$(cat "file.sql")

and

for Q in "${query[@]}"; do ..... something done

now it is now it is sending all select lines in one go instead of one at the time



标签: bash shell