Shell – Create list of folders with a matching (but not identical) ending

shell-script

I have a directory that contains folders ending in .ctpre or .ctpost (e.g. "15.ctpre"), along with other files/folders. I want to make a list that includes only subjects with both pre and post folders, and I only want to keep the matching subject ID (e.g. "15").

Here is the code I have right now:

#Make a list of folders that include .ct
find *.ct* -maxdepth 0 -fprint temp1
#In this list, remove the .ctpre and .ctpost extensions
sed 's/.ctpre//' temp1 > temp2
sed 's/.ctpost//' temp2 > temp3
#Sort the list
sort temp3 > temp4
#Print/save only duplicate entries on the list
uniq -d temp4 > sub_list
#Delete temp files
rm temp1 | rm temp2 | rm temp3 | rm temp4

Is there a more efficient way to do this?

Best Answer

All your script in one line

for file in *.ctp{ost,re} ; do echo ${file%.*} ; done | sort | uniq -d > sub_list

Or (thanks to drewbenn for comment)

for f in *.ctpre; do [ -d ${f%.*}.ctpost ] && echo ${f%.*} ; done > sub_list