Search code examples
bashfor-loopmove

bash script to loop through different files and perform command


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


Solution

  • 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