0

I have sub folders which contain 3 .txt files. Is it possible to choose only the 3rd file of each sub folder? Actually I want to copy and rename/add"e" at the end of each filename.Only on 3rd file of each folder. this is the foldering

New folder/20130903/ELF:

Naqs_20130901.txt
Naqs_20130902.txt
Naqs_20130903.txt

New folder/20130904/ELF:

Naqs_20130902.txt
Naqs_20130903.txt
Naqs_20130904.txt

and i will only do it in 3rd file

  • Since there are exactly three files per directory, just pick the last one: for d in $(find . -maxdepth 1 -type d) ; do last=$(ls "$d" | tail -1); echo mv "$d/${last}" "$d/${last}e"; done (remove the echo to actually perform the rename operation). This uses the default lexical sorting of ls, so YMMV. – phg Jul 4 '16 at 8:21
  • What do you mean the third folder, that is arbitrary based on how you are sorting them.? – 123 Jul 4 '16 at 8:41
  • I mean I have mutiple folders which contain 3 text file each folder and i will add e at the end of filename of every 3rd file inside the folder. – p_p Jul 4 '16 at 8:47
  • 1
    Yes, but how are you deciding which is the third folder... ? – 123 Jul 4 '16 at 8:48
  • 2
    How are you deciding which is the 3rd file? – JigglyNaga Jul 4 '16 at 8:51
2

If you're using bash, this can be done by filename expansion inside an array:

for dir in New\ folder/20130903/ELF New\ folder/20130904/ELF ; do
    files=( "$dir"/* )   # store all matching filenames in an array
    echo "${files[2]}"    # use 3rd element (subscripts are 0-based)
done

This outputs

New folder/20130903/ELF/Naqs_20130903.txt
New folder/20130904/ELF/Naqs_20130904.txt

Replace the echo line with whatever command you need to run on those files:

mv "${files[2]}" "${files[2]}e"
  • this works but it only works if i write "20130903/ELF" "20130904/ELF". What if i also have folders with 20130905 and many more, is there a way it can see all folders with 2013????. I tried to edit your command using your "2013????/ELF" instead of using 20130903 and 20130904 but i think it can 't read it. – p_p Jul 5 '16 at 8:14
  • I put those in quotes because of the space in New folder, but that prevents filename expansion (using the ? or * wildcards). I've edited to escape the space instead - so New\ folder/2013????/ELF should work. Alternatively, you could quote only the bit with a space: "New folder/"2013????/ELF – JigglyNaga Jul 5 '16 at 8:55

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.