Iterate through folders with names like folder0100, folder0101 to folder1100 in shell script

StackOverflow https://stackoverflow.com/questions/16784218

  •  30-05-2022
  •  | 
  •  

Domanda

I wrote a small shell script to iterate through folder with names having numbers in them. The script is as below.

#!/bin/bash
for (( i = 100; i < 1000; i++))
do
    cp test0$i/test.out executables/test0$i.out
done

here he script traverses through test0100 .. to test0999. I want to enhance this script to traverse from test0000 to test1100 folders. I am not able to do that.

I am new to shell scripting. Any help is appreciated.

È stato utile?

Soluzione

Using seq:

for i in $(seq -w 0 1100); do
    cp test$i/test.out executables/test$i.out
done

with the -w flag seq pads generated numbers with leading zeros such that all numbers have equal length.

Altri suggerimenti

How about this -

#!/bin/bash
for (( i = 0; i < 1100; i++))
do
    cp test$(printf "%04d" $i)/test.out executables/test$(printf "%04d" $i).out
done

With a recent bash

#!/bin/bash
for i in {0000..1100}; do
do
    cp test$i/test.out executables/test$i.out
done

Note that brace expansion occurs before variable expansion (see the manual) so if you want to do

start=0000
stop=1100
for i in {$start..$stop}

that won't work. In that case, use seq

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top