Home > Blockchain >  Take a list of names from a text file and compare them with a list of directories in Bash
Take a list of names from a text file and compare them with a list of directories in Bash

Time:04-03

I am trying to take a list of names from a text file and compare them with a list of directories. If there is a match in the directories then move them.

The code below doesn't work but it is essentially what I am trying to achieve.

#!/bin/bash

echo "Starting"

names="names.txt"

while IFS= read -r directory; do
        find 'Folder/' -type d -name '$directory' -print0
done < "$names" | xargs -t mv Folder/ MoveTo/

Example folder structure:

Folder/
 folder1
 folder2
 folder3
 oddfolder
 oddfolder2

MoveTo/
(empty)

Example text file structure:

 folder1
 folder2
 folder3

Output expectation:

Folder/
 oddfolder
 oddfolder2

MoveTo/
 folder1
 folder2
 folder3

I don't have an issue with spaces or capitalization. If there is a match then I want to move the selected folders to a different folder.

CodePudding user response:

This should work:

$ tree
├── folder
│   ├── f1
│   ├── f2
│   ├── f3
│   ├── f4
│   ├── other1
│   └── other2
├── name.txt
└── newdir

$ cat name.txt 
f1
f2
f3
f4

$ while IFS= read -r dir; do 
  mv "folder/$dir" newdir/. 2>/dev/null
done < name.txt

$ tree
.
├── folder
│   ├── other1
│   └── other2
├── name.txt
└── newdir
    ├── f1
    ├── f2
    ├── f3
    └── f4

Note that you should also use " instead of ' with variable

CodePudding user response:

You do not have to execute find command within the while loop. The test [[ -d dirname ]] will be enough to confirm the existence of the directory. Would you please try:

#!/bin/bash

names="names.txt"
src="Folder"
dest="MoveTo"

while IFS= read -r dir; do
   [[ -d $src/$dir ]] &&  mv "$src/$dir" "$dest"
done < "$names"
  • Related