Bash - check for a string in file path

折月煮酒 提交于 2019-12-08 15:22:22

问题


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.


回答1:


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 /.




回答2:


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


来源:https://stackoverflow.com/questions/34009549/bash-check-for-a-string-in-file-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!