Bash - check for a string in file path

2019-06-14 15:29发布

How can I check for a string in a file path in bash? I am trying:

if [[$(echo "${filePathVar}" | sed 's#//#:#g#') == *"File.java"* ]]

to replace all forward slashes with a colon (:) in the path. It's not working. Bash is seeing the file path string as a file path and throws the error "No such file or directory". The intention is for it to see the file path as a string.

Example: filePathVar could be

**/myloc/src/File.java

in which case the check should return true.

Please note that I am writing this script inside a Jenkins job as a build step.

Updates as of 12/15/15

The following returns Not found, which is wrong.

#!/bin/bash
sources="**/src/TESTS/A.java **/src/TESTS/B.java"

if [[ "${sources}" = ~B.java[^/]*$ ]];
then
echo "Found!!"
else
echo "Not Found!!"
fi

The following returns Found which also also wrong (removed the space around the comparator =).

#!/bin/bash
sources="**/src/TESTS/A.java **/src/TESTS/C.java"

if [[ "${sources}"=~B.java[^/]*$ ]];
then
echo "Found!!"
else
echo "Not Found!!"
fi

The comparison operation is clearly not working.

2条回答
时光不老,我们不散
2楼-- · 2019-06-14 15:49

It is easier to use bash's builtin regex matching facility:

$ filePathVar=/myLoc/src/File.java
if [[ "$filePathVar" =~ File.java[^/]*$ ]]; then echo Match; else echo No Match; fi
Match

Inside [[...]], the operator =~ does regex matching. The regular expression File.java[^/]* matches any string that contains File.java optionally followed by anything except /.

查看更多
祖国的老花朵
3楼-- · 2019-06-14 15:53

It worked in a simpler way as below:

#!/bin/bash
sources="**/src/TESTS/A.java **/src/TESTS/B.java"
if [[ $sources == *"A.java"* ]]
then
echo "Found!!"
else
echo "Not Found!!"
fi
查看更多
登录 后发表回答