LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Excluding existing folders in bash (https://www.linuxquestions.org/questions/linux-general-1/excluding-existing-folders-in-bash-4175560971/)

rng 12-08-2015 10:53 AM

Excluding existing folders in bash
 
I have a list of directories in a file:

Code:

/root
/boot
/sys
/a_dir
/b_dir

I want to remove already existing directories from this list:

Code:

/a_dir
/b_dir

How can I do this? I know xargs can deal with one line at a time and [ -d dirname ] will show if the dirname is present. So I tried:

Code:

cat dirlist | xargs -I {} [ -d {} ]
but it does not work. Thanks for your help.

HMW 12-08-2015 01:48 PM

I don't understand the question. Why don't you simply delete the unwanted entries using sed?

Code:

$ echo "/root
/boot
/sys
/a_dir
/b_dir" | sed '/\/[a-b]_dir/d'
/root
/boot
/sys

But I am probably missing something...

Best regards,
HMW

rng 12-08-2015 06:54 PM

The filter should check if that directory exists. If it does not exist, only then its name should be printed, else not. It could be something like:

Code:

cat dirlist | awk 'if( [ ! -d $1 ] ) print ($1)'
How can this awk code be corrected or any other method can be used?

onlyesterday16 12-08-2015 08:13 PM

I think you need use a loop:
Code:

for dir in $(cat dirlist); do
        if [ ! -d $dir ]; then
                do smt
        fi
done


rng 12-08-2015 09:59 PM

Thanks. I also managed using awk as follows:

Code:

cat dirlist | awk ' { if ( system(" [ -d " $1 " ] ")  ) print $1 } '


All times are GMT -5. The time now is 06:32 AM.