Home > other >  Extract a word from string in a certain position in bash script
Extract a word from string in a certain position in bash script

Time:01-10

I am writing a custom pre-push hook and want to extract a certain word from a commit message in a certain position. An example commit messages structure is

  • GRP-0876 CHANGE CORE - (core/components/button) : Some message
  • GRP-0876 CHANGE SHARED - (shared/components/button) : Some message
  • GRP-0876 CHANGE BUS - (pages/login) : Some message

GRP-0876 - the number here can be of any length. CORE - is one of the main folders in the root. It can be one of the CORE|SHARED|CSR|ADM|BUS

I need to extract the changed root folder ( In the below example it's CORE ) and assign it to a variable. I have done a lot of research and tried out a few examples, but none worked for me.

I have tried a sed command but the output is the same commit message.

echo 'GRP-0888 CHANGE CORE - (core/components/button) : Change button dimensions' | sed -n '/CORE/'

Even though my approach is not working, I would like to make it dynamic by extracting at a specified position with the help of regex

P.S.

I am writing a bash script for the first time.

EDITED

I need to extract that value and assign to a variable

app='GRP-0888 CHANGE CORE - (core/components/button) : Change button dimensions' | sed -E 's/.* \w  ([^[:blank:]] ) .*/\1/'
echo "$app"

This prints an empty string.

CodePudding user response:

Using this sed solution on the 3 lines you provided:

sed -E 's/.* (FIX|FEATURE|CHANGE|HOTFIX) ([^[:blank:]] ) .*/\2/' file

CORE
SHARED
BUS

To store this value in a variable:

app=$(echo 'GRP-0888 CHANGE SHARED - (core/components/button) : Change button dimensions' |
sed -E 's/.* (FIX|FEATURE|CHANGE|HOTFIX) ([^[:blank:]] ) .*/\2/')

Alternatively this awk should also work:

awk '$2 ~ /^(FIX|FEATURE|CHANGE|HOTFIX)$/ {print $3}' file

Where:

cat file

GRP-0876 CHANGE CORE - (core/components/button) : Some message
GRP-0876 CHANGE SHARED - (shared/components/button) : Some message
GRP-0876 CHANGE BUS - (pages/login) : Some message

CodePudding user response:

Using a while loop:

while read -r a b c d ; do echo "$c" ; done < msgs.txt
CORE
SHARED
BUS

or capture in variable:

 app=$(while read -r a b c d ; do echo "$c" ; done <<<"GRP-0888 CHANGE CORE - (core/components/button) : Change button dimensions")
echo "$app"
CORE
  • Related