bash command interpreter is really awesome, so why continuing to abuse the usage of “awk”; “sed”; “grep” and others ?

From now, begin a new life : let’s arrays take over in your scripts !

For example

From this file :

wou@ubuntu:~$ cat person
name : wou
firstname : frederic

name : wou
gender : male

name : wou
age : 40

name : wou
address :
street :

name : wou
address :
zip code : 74370

name : wou
address :
city : argonay

name : wou
address :
country iso code : fr

name : wou
address :
country : france

We would like to extract : the name and the name of the city.

Read the file in an text array

Here the script to do that :

wou@ubuntu:~$ cat array_sample.sh
#!/usr/bin/env bash

FILE="person"

#---------- read the file an a text array ----------
FORMER_IFS=$IFS IFS=$'\n' # $IFS backup
IFS=$'\n' # $IFS set now to "line feed"
unset RESULT_ARRAY ; declare -a RESULT_ARRAY
mapfile -t RESULT_ARRAY < <(grep -v "^$" $FILE)
IFS=$FORMER_IFS # $IFS set to its previous value

#---------- we can read this text array ----------
printf "we have read ${#RESULT_ARRAY[@]} non blank lines :\n\n"
for ((INDEX=0;INDEX != ${#RESULT_ARRAY[@]};INDEX++)) ; do
  printf "\"${RESULT_ARRAY[INDEX]}\"\n"
done

Pay your attention : $IFS is the delimiter, we need to set it to “line feed” in order to get one line per reccord.

Execute this script :

wou@ubuntu:~$ ./array_sample.sh
we have read 21 non blank lines :

"name : wou"
"firstname : frederic"
"name : wou"
"gender : male"
"name : wou"
"age : 40"
"name : wou"
"address :"
"street :"
"name : wou"
"address :"
"zip code : 74370"
"name : wou"
"address :"
"city : argonay"
"name : wou"
"address :"
"country iso code : fr"
"name : wou"
"address :"
"country : france"

Great, it did exactly what we wanted …

 

PDF24    Send article as PDF   

Leave a Reply

Your email address will not be published. Required fields are marked *


*