Bash – For loop inside another doesn’t work

bashfor

#! /bin/bash
for (( l = 1 ; l <= 50; ++l )) ; do
       for (( k = 1 ; k <= 1000; ++k )) ; do
       sed -n '$l,$lp' $k.dat >> ~/Escritorio/$l.txt
       done
done

The script is located in a folder together with 1000 dat files each one having 50 lines of text.

The dat files are called 1.dat, 2.dat,…., 1000.dat

My purpose is to make files l.txt, where l.txt has the l line of 1.dat, the l line of 2.dat, etc. For that, I use the sed command to select the l file of each dat file.

But when I run the above script, the txt created have nothing inside…

Where is the mistake?

Best Answer

for LINE in {1..50}; do
    for FILE in {1..1000}; do
        sed -n "${LINE}p" "${FILE}.dat" >>"~/Escritorio/${LINE}.dat"
    done
done

In your script you are using single quotes for the sed expression, variables don't expand inside single quotes, you need to use double quotes.

Also there is a one liner with awk that can do the same:

awk 'FNR<=50 {filename=sprintf("results/%d.dat", FNR); print >> filename; close(filename)}' *.dat

Just create the results directory, or change it in the command to another one, ~ does not expand to home there.

Related Question