1

I have 25 files in a directory, all named xmolout1, xmolout2, ... , xmolout25.

These are all .txt files and I need to copy the last 80 lines from these files to new .txt files.

Preferably, these would automatically generate the correct number (taken from the original file, e.g. xmolout10 would generate final10 etc.).

The original files can be deleted afterwards.

I am a newbie in bash scripting, I know I can copy the last 80 lines using tail -80 filename.txt > newfilename.txt, but I don't know how to implement the loop.

Thanks in advance

Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
Steven
  • 404
  • 1
  • 3
  • 10
  • Have you tried anything? I put the exact title of this question into a search engine and the first hit gave me the answer... – arco444 Aug 13 '15 at 09:19
  • I did, and the general answer as provided by the first hit, is the one that is presented here. It is the same as I had, but I didn't know how to loop automatically through the 25 files... As I mentioned, I have never ever written something that is even close to a "script". – Steven Aug 13 '15 at 09:25

1 Answers1

2

If you know the number of files to be processed, you could use a counter variable in a loop:

for ((i=1; i<=25; i++))
do
    tail -80 "xmolout$i" >> "final$i"
done

If you want to remain compatible with shells other than bash you can use this syntax:

for i in {1..25}
do
    tail -80 "xmolout$i" >> "final$i"
done
user000001
  • 32,226
  • 12
  • 81
  • 108
  • Thank you, the second answer is the best option in this case :) – Steven Aug 13 '15 at 09:21
  • @StevenVanuytsel Yes the second syntax looks better, but keep in mind that (in the 2nd syntax) the brackets are expanded *before* the loop is invoked, so if your loop becomes too long, it is slower than the first syntax. It also doesn't work with variables as bounds. – user000001 Aug 13 '15 at 09:59