Home > OS >  Remove set of special chars from a string using bash script
Remove set of special chars from a string using bash script

Time:10-09

I need to search for the file path ending with *Tests.cs having multiple directories. I need to display all the file path in spaces instead of new line. Currently, it is displaying as

./dir1/bin/dir1Tests.cs ./dir2/bin/dir2Tests.cs

How to remove ./ from each file path and display it as follows?

dir1/bin/dir1Tests.cs dir2/bin/dir2Tests.cs

My bash script is:

FILES=$(find . -path '*bin/*' -name *Tests.cs -type f -printf "%p ")
echo $FILES

CodePudding user response:

If your structure is consistent as in the example, it's easy.

$: echo */bin/*Tests.cs
dir1/bin/dir1Tests.cs dir2/bin/dir2Tests.cs

If there are arbitrary, varying depths, use globstar.

$: shopt -s globstar               # make ** register arbitrary depth subdirs

Then use double-asterisks for arbitrary depths.

$: echo **/*bin/**/*Tests.cs
dir1/bin/dir1Tests.cs dir1/subdir/bin/another/deeperTests.cs dir2/bin/dir2Tests.cs

None of that requires a find.

If you just need to do some other editing, pattern expansion works fine.

files=( ./**/*bin/**/*Tests.cs ) # sticking the unnecessary ./ on to remove
echo "${files[@]#./}"            # strip it from each element as processed
dir1/bin/dir1Tests.cs dir1/subdir/bin/another/deeperTests.cs dir2/bin/dir2Tests.cs
  • Related