I have some data stored in a flat file, similar to the data which is shown below. I need to be able to extract the data into variables, such as the variable AGE being equal to 24 and the variable user being equal to user01. I also need to be able to tell which database the data is for, such as db[0] and db[1] and so on.
db[0].age="24"
db[0].user="user01"
db[0].password="pasword01"
db[0].office="usa office 1"
db[1].age="44"
db[1].userID="user01"
db[1].userPW="password02"
db[1].office="uk office 2"
What I've done so far is to use awk to search for all instances of age and extract the number is the square brackets into an array.
databaseCount=($(awk '/'"age"'/' flatFile | cut -d "[" -f2 | cut -d "]" -f1))
I was then thinking using a similar awk to extract the text found in the brackets and put that data into an array.
age=($(awk '/'"dbUserAlias"'/' flatFile | cut -d\" -f2))
I was then planning on using the databaseCount to find the data for weach array, so I would know that the data found in element 0 of the age array is for database 0 and the data found in element 1 is ofr database 1.
The problem that I'm having is that some of the text found between the speech marks has spaces.
echo ${office[0]}
Would return "uk" instead of "uk office 2".
Does anyone know how to fix this, or if there is a better way to extract the data?
Thank you.
如果以这种方式访问数组,则应将元素封装在双引号中,用以下代码替换代码:
age=($(printf "\"$(awk '/'"dbUserAlias"'/' flatFile | cut -d\" -f2)\""))
When the flatFile was formatted like
age="24"
you could have sourced that file.
When you ignore the db[n]
, you can use
. <(cut -d"." -f2- flatFile)
Now we want to split up the file for each db and process the lines for each db:
for db in {0..5}; do
sourcelines=$(grep "^db\[${db}\]" flatFile)
if [[ -n "${sourcelines}" ]]; then
echo "Database db[${db}]"
. <(cut -d"." -f2- <<< "${sourcelines}" )
# show the variables that have been set
set | grep -E "^age=|^userID=|^userPW=|^office=" | sort
fi
done
When you want to use different variables for different databases, you need a small change:
for db in {0..5}; do
sourcelines=$(grep "^db\[${db}\]" flatFile)
if [[ -n "${sourcelines}" ]]; then
echo "Database db[${db}]"
. <(echo -e "${sourcelines}" | tr "\[\]\." "_")
# show the variables that have been set
set | grep -E "^db_${db}_" | sort
fi
done
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.