Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get directory when last folder in path ends in given string (sed in ifelse)

I am attempting to find multiple files with .py extension and grep to see if any of these files contain the string nn. Then return only the directory name (uniques), afterwards, if the last folder of the path ends in nn, then select this.

For example:

find `pwd` -iname '*.py' | xargs grep -l 'nn' | xargs dirname | sort -u | while read files; do if [[ sed 's|[\/](.*)*[\/]||g' == 'nn' ]]; then echo $files; fi; done

However, I cannot use sed in if-else expression, how can I use it for this case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

[[ ]] is not bracket syntax for an if statement like in other languages such as C or Java. It’s a special command for evaluating a conditional expression. Depending on your intentions you need to either exclude it or use it correctly.

If you’re trying to test a command for success or failure just call the command:

if command ; then
  :
fi

If you want to test the output of the command is equal to some value, you need to use a command substitution:

if [[ $( command ) = some_value ]] ; then
  :
fi

In your case though, a simple parameter expansion will be easier:

# if $files does not contain a trailing slash
if [[ "${files: -2}" = "nn" ]] ; then
  echo "${files}"
fi

# if $files does contain a trailing slash
if [[ "${files: -3}" = "nn/" ]] ; then
  echo "${files%/}"
fi
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading