bash regex patch match - regex

I have a path such as thus ..
/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java
I'd like to be able to use bash to create the package structure in another dir somewhere e.g.
com/mecorp/sub/misc/
I tried the following but it wont work .. I was able to get a match if I change my regex to .* so that implies my bash is ok - There must be something wrong with the way im quoting the regex or maybe the regex its self. I do see working here ..
http://regexr.com?3439m
So im confused ?
regex="(?<=/java)(.*)(?=/)"
[[ $fullfile =~ $regex ]]
echo "pkg name " ${BASH_REMATCH[0]}
Thanks for your time.
EDIT - I'm using OSX so it doesn't have all those nice spiffy GNU extensions.

Try this :
using GNU grep :
$ echo '/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java' |
grep -oP 'java/\K.*/'
com/mecorp/sub/misc/
See http://regexr.com?3439p
Or using bash :
x="/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java"
[[ $x =~ java/(.*/) ]] && echo ${BASH_REMATCH[1]}
Or with awk :
echo "$x" | awk -F/ '{print gensub(".*/java/(.*/).*", "\\1", $0)}'
Or with sed :
echo "$x" | sed -e 's#.*/java/\(.*/\).*#\1#'

If you try to extract the path after /java/ you can do it with this:
path=/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java
package=`echo $path | sed -r 's,^.*/java/(.*/).*$,\1,'`

Related

How to use regex capturing group in bash correctly?

I've loaded some strings into variable "result". The strings look like this:
school/proj_1/file1.txt
school/proj_1/file2.txt
school/proj_1/file3.txt
I try to get only the name after the last slash, so file1.txt, file2.txt and file3.txt is the desirable result for me. I use this piece of code
for i in $result
do
grep "school/proj_1/(.*)" $i
done
but it doesn't work. I feel that the regex would work for Python with the caputuring group I created, but I can't really wrap my head around how to use capturing groups in bash or if it is even possible at all.
I'm sorry if it's a dumb question, I'm very new to scripting in bash.
You may use a simple approach with a string manipulation operation:
echo "${i##*/}"
${string##substring}
Deletes longest match of $substring from front of $string.
Or using a regex in Bash, you may get the capturing groups like
result=("school/proj_1/file1.txt" "school/proj_1/file2.txt" "school/proj_1/file3.txt")
rx='school/proj_1/(.*)'
for i in "${result[#]}"; do
if [[ "$i" =~ $rx ]]; then
echo "${BASH_REMATCH[1]}"
fi
done
See the online demo. Here, ${BASH_REMATCH[1]} is the contents inside capturing group #1.
Try this :
variable declaration :
$ result="school/proj_1/file1.txt
school/proj_1/file2.txt
school/proj_1/file3.txt"
Commands :
(all as one-liners)
$ grep -oP "school/proj_1/\K.*" "$i" <<< "$result"
or
$ awk -F'/' '{print $NF}' <<< "$result
or
$ sed 's|.*/||' <<< "$result"
or if number of sub dirs are fixed :
$ cut -d'/' -f3 <<< "$result"
Output :
file1.txt
file2.txt
file3.txt

how to match regex in bash script with for loop?

I'm trying to match multiple strings from output of a command and do something for each one of them.
#!/usr/bin/env bash
echo 'Howdy, can you please give me the domain (without www)?'
read domain
routes=$(flynn -a shop-app route | grep $domain)
# echo $routes | egrep "http\/\S+"
pattern="http\/[^ ]+"
for word in $routes
do
[[ $word =~ $pattern ]]
if ${BASH_REMATCH[0]}
then
match="${BASH_REMATCH[0]}"
sed -i s/DOMAIN/$domain/g $domain.sh
sed -i s:ROUTE1:$match:g $domain.sh
fi
if ${BASH_REMATCH[1]}
then
match2="${BASH_REMATCH[1]}"
sed -i s:ROUTE2:$match2:g $domain.sh
fi
done
echo $match
update: the regex part works now but the loop is not working. I know the loop will find two match and want to do something with each one
the sample text:
http:www.lipi.ir shop-app-web http/d49ced12-c6ca-46a0-b919-6d97b6580ad3 false false /
http:lipi.ir shop-app-web http/ff919e9d-9bf7-4342-a4b3-ea184c698959 false false /

bash - Extract part of string

I have a string something like this
xsd:import schemaLocation="AppointmentManagementService.xsd6.xsd" namespace=
I want to extract the following from it :
AppointmentManagementService.xsd6.xsd
I have tried using regex, bash and sed with no success. Can someone please help me out with this?
The regex that I used was this :
/AppointmentManagementService.xsd\d{1,2}.xsd/g
Your string is:
nampt#nampt-desktop:$ cat 1
xsd:import schemaLocation="AppointmentManagementService.xsd6.xsd" namespace=
Try with awk:
cat 1 | awk -F "\"" '{print $2}'
Output:
AppointmentManagementService.xsd6.xsd
sed doesn't recognize \d, use [0-9] or [[:digit:]] instead:
sed 's/^.*schemaLocation="\([^"]\+[[:digit:]]\{1,2\}\.xsd\)".*$/\1/g'
## or
sed 's/^.*schemaLocation="\([^"]\+[0-9]\{1,2\}\.xsd\)".*$/\1/g'
You can use bash native regex matching:
$ in='xsd:import schemaLocation="AppointmentManagementService.xsd6.xsd" namespace='
$ if [[ $in =~ \"(.+)\" ]]; then echo "${BASH_REMATCH[1]}"; fi
Output:
AppointmentManagementService.xsd6.xsd
Based on your example, if you want to grant, at least, 1 or, at most, 2 digits in the .xsd... component, you can fine tune the regex with:
$ if [[ $in =~ \"(AppointmentManagementService.xsd[0-9]{1,2}.xsd)\" ]]; then echo "${BASH_REMATCH[1]}"; fi
using PCRE in GNU grep
grep -oP 'schemaLocation="\K.*?(?=")'
this will output pattern matched between schemaLocation=" and very next occurrence of "
Reference:
https://unix.stackexchange.com/a/13472/109046
Also we can use 'cut' command for this purpose,
[root#code]# echo "xsd:import schemaLocation=\"AppointmentManagementService.xsd6.xsd\" namespace=" | cut -d\" -f 2
AppointmentManagementService.xsd6.xsd
s='xsd:import schemaLocation="AppointmentManagementService.xsd6.xsd" namespace='
echo $s | sed 's/.*schemaLocation="\(.*\)" namespace=.*/\1/'

Regular expression to grab Red Hat release version

Running command uname -r gives us:
3.10.0-229.14.1.el7.x86_64
I need to extract "el7". I'm not that great with regexp and could use a helping hand. If you could, explain what is going on in the solution.
Thank you
In BASH you can use this regex:
s='3.10.0-229.14.1.el7.x86_64'
[[ $s =~ ([^.]+)\.[^.]+$ ]] && echo "${BASH_REMATCH[1]}"
el7
Or without regex using awk:
uname -r | awk -F '.' '{print $(NF-1)}'
el7

Return a regex match in a Bash script, instead of replacing it

I just want to match some text in a Bash script. I've tried using sed but I can't seem to make it just output the match instead of replacing it with something.
echo -E "TestT100String" | sed 's/[0-9]+/dontReplace/g'
Which will output TestTdontReplaceString.
Which isn't what I want, I want it to output 100.
Ideally, it would put all the matches in an array.
edit:
Text input is coming in as a string:
newName()
{
#Get input from function
newNameTXT="$1"
if [[ $newNameTXT ]]; then
#Use code that im working on now, using the $newNameTXT string.
fi
}
You could do this purely in bash using the double square bracket [[ ]] test operator, which stores results in an array called BASH_REMATCH:
[[ "TestT100String" =~ ([0-9]+) ]] && echo "${BASH_REMATCH[1]}"
echo "TestT100String" | sed 's/[^0-9]*\([0-9]\+\).*/\1/'
echo "TestT100String" | grep -o '[0-9]\+'
The method you use to put the results in an array depends somewhat on how the actual data is being retrieved. There's not enough information in your question to be able to guide you well. However, here is one method:
index=0
while read -r line
do
array[index++]=$(echo "$line" | grep -o '[0-9]\+')
done < filename
Here's another way:
array=($(grep -o '[0-9]\+' filename))
Pure Bash. Use parameter substitution (no external processes and pipes):
string="TestT100String"
echo ${string//[^[:digit:]]/}
Removes all non-digits.
I Know this is an old topic but I came her along same searches and found another great possibility apply a regex on a String/Variable using grep:
# Simple
$(echo "TestT100String" | grep -Po "[0-9]{3}")
# More complex using lookaround
$(echo "TestT100String" | grep -Po "(?i)TestT\K[0-9]{3}(?=String)")
With using lookaround capabilities search expressions can be extended for better matching. Where (?i) indicates the Pattern before the searched Pattern (lookahead),
\K indicates the actual search pattern and (?=) contains the pattern after the search (lookbehind).
https://www.regular-expressions.info/lookaround.html
The given example matches the same as the PCRE regex TestT([0-9]{3})String
Use grep. Sed is an editor. If you only want to match a regexp, grep is more than sufficient.
using awk
linux$ echo -E "TestT100String" | awk '{gsub(/[^0-9]/,"")}1'
100
I don't know why nobody ever uses expr: it's portable and easy.
newName()
{
#Get input from function
newNameTXT="$1"
if num=`expr "$newNameTXT" : '[^0-9]*\([0-9]\+\)'`; then
echo "contains $num"
fi
}
Well , the Sed with the s/"pattern1"/"pattern2"/g just replaces globally all the pattern1s to pattern 2.
Besides that, sed while by default print the entire line by default .
I suggest piping the instruction to a cut command and trying to extract the numbers u want :
If u are lookin only to use sed then use TRE:
sed -n 's/.*\(0-9\)\(0-9\)\(0-9\).*/\1,\2,\3/g'.
I dint try and execute the above command so just make sure the syntax is right.
Hope this helped.
using just the bash shell
declare -a array
i=0
while read -r line
do
case "$line" in
*TestT*String* )
while true
do
line=${line#*TestT}
array[$i]=${line%%String*}
line=${line#*String*}
i=$((i+1))
case "$line" in
*TestT*String* ) continue;;
*) break;;
esac
done
esac
done <"file"
echo ${array[#]}