0

I want to copy some files from a remote computer into my own computer. These files have the following structure:

file00001sub0
file00001sub1
file00001sub2
file00123sub0
file00123sub1
file00123sub2

I am currently copying them with a script.sh:

 scp me@computer:file${1}sub* ./

Which means that I have to do things like script.sh 00001 and script.sh 00123

How can I make this work with trailing zeros? The number of digits is currently fixed, so I could in principle add the zeros by hand in the script, but there has to be a better way.

user17004502
  • 105
  • 1
  • 6
  • @KamilCuk You are right. My mistake, thanks. – user17004502 Nov 15 '21 at 16:39
  • Does https://stackoverflow.com/questions/18460123/how-to-add-leading-zeros-for-for-loop-in-shell answer your question? – KamilCuk Nov 15 '21 at 16:40
  • taking into consideration your various comments and thinking about this a bit more ... I'm wondering if what you want is something like: `shopt -s extglob ; scp ...:file*([0])${1}sub* ...`, but how to pass the `shopt/extglob/*([0])` to the remote host? if this is more along the lines of what you're looking for ... perhaps create a new question asking how to pass a `extglob` (via `scp`) to a remote host? – markp-fuso Nov 15 '21 at 17:31
  • spitballing ... perhaps run the `scp` from the remote host ... something like: `ssh me@computer "shopt -s extglob; scp files*([0])${1}sub* me@localhost:/path/to/dir"` – markp-fuso Nov 15 '21 at 17:40

1 Answers1

1

I'd use printf -v to create a new 0-padded variable, eg:

$ x=254
$ printf -v newx "%05s" "${x}"
$ echo "${newx}"
00254

Addressing OP's additional requirement of supporting a variable number of digits ...

Assumption: OP can determine the number of digits

$ n=6               # number of digits
$ x=284
$ printf -v newx "%0*s" "${n}" "${x}"
$ echo "${newx}"
000284
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • That works only assuming that you know the number of digits is fixed, right? This completely solves my problem (until the number of digits increases). It would be good to have a more robust answer for an unknown number of leading zeros. – user17004502 Nov 15 '21 at 16:55
  • how would you know what the number of digits is supposed to be, especially if you don't have access to the remote file names prior to running the `scp` command? – markp-fuso Nov 15 '21 at 16:56
  • That is the entire point of my question. For example wildcard `*` matches anything regardless of how long it is. I wanted to know if it is possible to match leading zeros. – user17004502 Nov 15 '21 at 17:00
  • For me this is filling the number of digits with empty space rather than 0s. It changes them to 0s with `%05i`, but this then fails with wildcard arguments like `x=55?` – user17004502 Nov 15 '21 at 19:30
  • I cut-n-pasted the code from above into my terminal ... both sets of code generate the same values as listed; I've used `%s` as I didn't want to assume `x` is numeric – markp-fuso Nov 15 '21 at 21:13