0

I have files with sections defined by the starting section composed oy TITLE, SUBTITLE, followed by comma separated KEYWORD.

## TITLE [SUBTITLE] KEYWORD,KEYWORD  

The ending is done using

## END OF TITLE [SUBTITLE]

I want to ensure that the file contains the corresponding closing part to the definition.

How can I make a test that check the file has things as should be. I need the test in bash.

## FAML [ASMB] keyword,keyword

Some text

Description

END OF FAML [ASMB]

Some Code

More text

FALUN [GONG] keyword,keyword

Some text

Description

END OF FALUN [GONG]

More Text

Have started with following to capture the actual strings for the corresponding section.

while read line; do
  if [[ $line =~ ^##\ ([A-Z]+)\ \[([A-Z]+)\]\ (.*),(.*)$ ]]; then
    title=${BASH_REMATCH[1]}
    subtitle=${BASH_REMATCH[2]}
    keywords=${BASH_REMATCH[3]}
    keywords2=${BASH_REMATCH[4]}
    echo "Title: $title"
    echo "Subtitle: $subtitle"
    echo "Keywords: $keywords, $keywords2"
  fi
done < input.txt

Attempted to run the code on the following, but the printing is not keywords array printing is not happening.

  ## DN [AMBIT] bash,resource
  ##   hodeuiihoedu
  ##   AVAL:
  ##   + ooeueocu
  ## END OF DN [AMBIT]
AdminBee
  • 22,803
Vera
  • 1,223

1 Answers1

0

To read an arbitrary number of keywords, change the regex to find a pattern of any text followed by optional comma. The complete list of keywords will be captured into a single variable. Then read the comma-separated list into an array.

while read -r line; do
    if [[ $line =~ ^##\ ([A-Z]+)\ \[([A-Z]+)\]\ (.*[,]?)$ ]]; then
        title="${BASH_REMATCH[1]}"
        subtitle="${BASH_REMATCH[2]}"
        echo "Title: $title"
        echo "Subtitle: $subtitle"
    # read keyword list into array
    IFS=',' read -ra keywords &lt;&lt;&lt; &quot;${BASH_REMATCH[3]}&quot;
    i=0
    for kw in &quot;${keywords[@]}&quot;; do
        echo &quot;Keyword$((i+=1)): $kw&quot;
    done
    echo
fi

done << EOF

FAML [ASMB] keyword1,keyword2

Some text

Description

END OF FAML [ASMB]

Some Code

More text

FALUN [GONG] keyword1,keyword2,keyword3,keyword4

Some text

Description

END OF FALUN [GONG]

EOF

Output:

Title: FAML
Subtitle: ASMB
Keyword1: keyword1
Keyword2: keyword2

Title: FALUN Subtitle: GONG Keyword1: keyword1 Keyword2: keyword2 Keyword3: keyword3 Keyword4: keyword4

floydn
  • 111