-2

I want to write code to read all the files present in a directory except a specific directory.

Directory path:

constellation/netcool/aws_netcool_db2/trunk/src

Under src, there are 3 directories (base , v1_version, v2_version, v3_version). I want to read all directory except base directory.

How do I solve this problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
  • 4
    Being a new SO user, I'll suggest you to please read [How to ask](https://stackoverflow.com/help/how-to-ask) and specifically [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) so it helps others and in turn they can help you back. – Pushpesh Kumar Rajwanshi Apr 17 '19 at 10:37
  • 1
    See also [Excluding certain directories with Find::File::Rule](https://stackoverflow.com/q/25008883/2173773) and [Perl File::Find::Rule excluding directories from an array](https://stackoverflow.com/q/21431191/2173773) and [File::Find::Rule to exclude a single dir only for the top level](https://stackoverflow.com/q/25895751/2173773) – Håkon Hægland Apr 17 '19 at 11:19

1 Answers1

0

Using find:

quotemeta() { printf '%s' "$1" | perl -0777ne'print quotemeta($_)'; }

path=constellation/netcool/aws_netcool_db2/trunk/src

find "$path" \
   -path "$( quotemeta "$path/base" )" \
   -prune \
-o \
   \! -type d \
   -print

Note that this doesn't work for paths starting with -. Prepend ./ to those.


Using Perl:

use File::Find::Rule qw( );

my $path = "constellation/netcool/aws_netcool_db2/trunk/src";

my $FFR = File::Find::Rule::;
my @files =
   $FFR->or(
      $FFR
         ->exec(sub{ $_[2] eq "$path/base" })
         ->prune
         ->discard,
      $FFR
         ->not( $FFR->directory ),
   )
      ->in($path);

Note that this doesn't work for all paths (e.g. ., those that end with /, etc) because F::F::R cleans up the paths. You would need to apply those same undocumented cleanups to the value against which $_[2] is compared if you wish to support arbitrary paths.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • It worked exactly the way I wanted. Thanks a ton :) – Angel Peehuu Apr 19 '19 at 11:27
  • The output contains the directories too. /opt/IBM/tivoli/netcool/AWS/DB2/sql_scripts /opt/IBM/tivoli/netcool/AWS/DB2/sql_scripts/v2_version /opt/IBM/tivoli/netcool/AWS/DB2/sql_scripts/v2_version/Rollback.sql /opt/IBM/tivoli/netcool/AWS/DB2/sql_scripts/v2_version/UpdateSchemaVersionHistory.sql /opt/IBM/tivoli/netcool/AWS/DB2/sql_scripts/v1_version /opt/IBM/tivoli/netcool/AWS/DB2/sql_scripts/v1_version/Rollback.sql /opt/IBM/tivoli/netcool/AWS/DB2/sql_scripts/v1_version/UpdateSchemaVersionHistory.sql How Can I get only file names? – Angel Peehuu Apr 19 '19 at 11:40