0

I have a series of files of the form:

test_0000.txt test_0001.txt ... test_0009.txt

and I would like to copy a subset of them to a sub directory

subdir/

It is my intention to use strings stored as variables and combine them to create the copy command, and use brace expansion to set the indexes I want to copy.

Here is my attempt at a solution:

prefix='test' 
suffix='.txt' 
imin=0 imax=9 
stride=4 
cp $prefix000{$imin..$imax..$stride}$suffix subdir/ 

however this yields:

cp: cannot stat '{0..9..4}.txt': No such file or directory 

There are two problems I see, the first being that $prefix and 000 might be interpreted as if I am referring to a variable $prefix000. The second being if I write this with quotations to avoid that issue:

cp $prefix'000'{$imin'..'$imax'..'$stride}$suffix' subdir/' 

then the brace expansion does not happen. My expected result from the command is:

cp test_0000.txt subdir/ 
cp test_0004.txt subdir/ 
cp test_0008.txt subdir/ 

Any help would be appreciated.

cddean
  • 1
  • Use of variables is not supported within the `{beg..end..inc}` brace expansion (you can cludge it using `eval`, but recall that is just 1-character away from `evil`). Instead use a utility like `seq` or `jot` where you can specify start/stop with variables. – David C. Rankin Mar 07 '23 at 23:33
  • You'll find an answer here: [Brace expansion with variable?](https://stackoverflow.com/questions/19432753/brace-expansion-with-variable) – tshiono Mar 07 '23 at 23:34
  • Brace expansion only works with literal numbers. A possible alternative is `for ((i=imin; i<=imax; i+=stride)); do cp -- "${prefix}000${i}${suffix}" subdir/; done` – pjh Mar 08 '23 at 01:52
  • Thank you for the help, I ended up using seq as recommended by @DavidC.Rankin: `for i in $(seq -f '%04.f' $imin $stride $imax) ; do cp $prefix$i$suffix subdir/ done` Which had the desired outcome. – cddean Mar 08 '23 at 16:01

0 Answers0