Issue
I've a file like this
Name: Test1
Acronym: TEST11
Description: null
Toolkit: false
Tracks:
List:
Name: 1st_test
Acronym: TEST11_1
Created On: 2016-03-22 15:25:27.355
Created By: User.9
Is Default: false
State: State[Inactive]
Capability: Capability[Standard]
No of running instances: 0
Name: 2nd_test
Acronym: TEST11_2
Created On: 2016-03-23 15:07:18.955
Created By: User.9
Is Default: true
State: State[Active]
Capability: Capability[Standard]
No of running instances: 0
Name: 3rd_test
Acronym: TEST11_3
Created On: 2016-03-22 11:54:45.276
Created By: User.9
Is Default: false
State: State[Inactive]
Capability: Capability[Standard]
No of running instances: 1
I need a script that prints Acronym (the one under List) if:
- line "Is Default" = false
- line "State" = Inactive
- line "No of running instances" = 0
From the example file provided I should expect only TEST11_1
Any help will be appreciated. Regards.
Solution
There are many ways to do this. One that comes to mind is to use grep
to parse the file and then loop through each list segment.
Here's a complete example:
#!/usr/bin/env bash
shopt -s extglob
# name of the file
file=file.txt
# extract the "Name: ..." lines of file
list_names="$(grep -E '\s+Name' "$file")"
list=()
# add each "Name: ..." line to the "list" array
while IFS= read -r line; do
# trim string
list+=("${line##*( )}")
done <<< "$list_names"
# check if all three conditions are met
function check {
grep --quiet --fixed-strings \
'Is Default: false' <<< "$1" &&
grep --quiet --fixed-strings \
'State: State[Inactive]' <<< "$1" &&
grep --quiet --fixed-strings \
'No of running instances: 0' <<< "$1"
}
# loop through each list segment and check
# if conditions are met for each one
for f in "${list[@]}"; do
# select and store all key/value pairs of each instance
settings="$(grep -A 7 "$f" "$file")"
# print "Acronym" value if all three strings
# are found in the check function
if check "$settings"; then
output="$(grep 'Acronym' <<< "$settings")"
# trim string
echo "${output##*( )}"
fi
done
The output of the script is Acronym: TEST11_1
, because TEST11_1
meets all three conditions. The conditions are defined in the check
function.
I'm not sure if this is clear enough, as the script became a bit verbose. If you have any questions, feel free to ask.
Answered By - dbran Answer Checked By - David Marino (WPSolving Volunteer)