how to create symlinks for all partial file name matches?

Viewed 74

I'm trying to create symlinks to all files in a list of file names, where the file names in the list only partially match the names of the files.

I have a list of partial file names (file_name_list.txt)

cat file_name_list.txt
>file_ABC
>file_DEF
>file_GHI

the files I want to link are in a folder that looks like this:

ls -l <path to original files>
>new_file_ABC.txt
>file_ABC.fasta
>OCTOBER_file_DEF.fa
>file_DEF.gff
>file_GHI.txt
>file_XYZ.txt

where the intended result would be :

ls -l <path to symlinked files>
new_file_ABC.txt
file_ABC.fasta
OCTOBER_file_DEF.fa
file_DEF.gff
file_GHI.txt

what I've tried:

while IFS= read -r file; do
    [[ -e <path to files>/*"$file"* ]] && ln -s <path to files>/*"$file"* .
 done < file_name_list.txt ```
1 Answers
files_dir="1"
links_dir="2"
f="filenames_list.txt"

find "$files_dir" -type f -printf "%f\0" | grep -zf "$f" |
    xargs -r0 -I{} ln -rs "$files_dir/{}" "$links_dir/{}"

Filter all filenames through a grep -f with the patterns list and create the links. All commands above use null separated arguments to preserve filanames.

In general, it is more useful to create links with relative path, as they will be still functional if you move a parent directory of both locations or mount it. To make this easy, use -r parameter with ln, while providing the arguments as they are.


example

filenames_list.txt:

file_ABC
file_DEF
file_GHI
mkdir -p 1
mkdir -p 2
touch 1/new_file_ABC.txt
touch 1/file_ABC.fasta
touch 1/OCTOBER_file_DEF.fa
touch 1/file_DEF.gff
touch 1/file_GHI.txt
touch 1/file_XYZ.txt
touch 1/file1.txt
touch 1/file2.txt

files_dir="1"
links_dir="2"
f="filenames_list.txt"

find "$files_dir" -type f -printf "%f\0" | grep -zf "$f" |
    xargs -r0 -I{} ln -rs "$files_dir/{}" "$links_dir/{}"

result ls for dir 2/

file_ABC.fasta -> ../1/file_ABC.fasta
file_DEF.gff -> ../1/file_DEF.gff
file_GHI.txt -> ../1/file_GHI.txt
new_file_ABC.txt -> ../1/new_file_ABC.txt
OCTOBER_file_DEF.fa -> ../1/OCTOBER_file_DEF.fa
Related