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?

  • Can you provide a list of sample filenames, and show the output you want? – glenn jackman Feb 6 '15 at 20:43
  • 2
    Note that rm doesn't do anything with stdin, so piping into it is not useful. You want rm temp1; rm temp2; rm temp3; rm temp4 or rm temp1 temp2 temp3 temp4 or rm temp{1,2,3,4} or rm temp[1-4] – glenn jackman Feb 6 '15 at 20:44
  • Example folder names: 15.ctpre, 15.ctpost, 16.ctpre, 17.ctpre, 17.ctpost. Example output: 15, 17 – Brent Womble Feb 8 '15 at 20:28
  • Thanks for the note about 'rm' and the variety of options. – Brent Womble Feb 8 '15 at 20:30

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
| improve this answer | |
  • 1
    @drewbenn It is subtle but Costas' use of uniq -d has the effect of a logical AND. – John1024 Feb 6 '15 at 20:54
  • @drewbenn nice idea, I'd like it. If you do not intend to make your own post I'l add it as variant – Costas Feb 6 '15 at 20:56
  • Thanks Costas and @drewbeen, all 3 of those lines worked. I didn't know about that output option for echo – Brent Womble Feb 8 '15 at 20:45
  • @Costas, in your second line, what does [ -d ${f%.*}.ctpost ] do? Does it work the same as test -d? – Brent Womble Feb 8 '15 at 20:47
  • 1
    @BrentWomble Yes, the [ is synonim of test – Costas Feb 9 '15 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.