1

I have 100s of files in a directory, and I want to keep only those where a part of first file matches with another file and if condition is not fulfilled than mv all files without its corresponding file, such as I have:

 man_xyz_1.txt 
 sig_xyz_1.txt 
 man_abc_1.txt 
 man_ttc_1.txt
 man_ddd_1.txt
 sig_ddd_1.txt

here, I want to keep only first two files (man_xyz_1.txt and sig_xyz_1.txt; man_ddd_1.txt and sig_ddd_1.txt) as their part of filenames (*_xyz_1.txt and *_ddd_1.txt) are matching while want to mv (man_abc_1.txt and man_ttc_1.txt) in to another directory as they don't have corresponding file with prefix sig_*. Any help is welcome. Thanks,

1 Answers1

1

This does the opposite, i.e. looks at all man_*.txt files in the current directory and moves all that can be paired up with a corresponding sig_ file to a processed directory. You can then move the remaining files wherever you need to store them.

mkdir processed || exit
for name in man_*.txt; do
    if [ -e "sig_${name#man_}" ]; then
        mv "$name" "sig_${name#man_}" processed
    fi
done

The parameter substitution ${name#man_} expands to the value of $name with its man_ prefix string removed.

Note that this assumes that the processed directory does not exist.

Testing:

$ tree
.
|-- man_abc_1.txt
|-- man_ddd_1.txt
|-- man_ttc_1.txt
|-- man_xyz_1.txt
|-- script
|-- sig_ddd_1.txt
`-- sig_xyz_1.txt

1 directory, 7 files

$ sh script
$ tree
.
|-- man_abc_1.txt
|-- man_ttc_1.txt
|-- processed
|   |-- man_ddd_1.txt
|   |-- man_xyz_1.txt
|   |-- sig_ddd_1.txt
|   `-- sig_xyz_1.txt
`-- script

2 directories, 7 files
Kusalananda
  • 333,661