Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to download files matching a pattern trough SFTP on shell script?

Tags:

linux

shell

sftp

I'm trying to download multiple files trough SFTP on a linux server using

sftp -o IdentityFile=key <user>@<server><<END
    get -r folder
    exit
END

which will download all contents on a folder. It appears that find and grep are invalid commands, so are for loops.

I need to download files having a name containing a string e.g.

test_0.txt

test_1.txt

but no file.txt

like image 734
mrOak Avatar asked Jan 27 '26 05:01

mrOak


2 Answers

Do you really need the -r switch? Are there really any subdirectories in the folder? You do not mention that.

If there are no subdirectories, you can use a simple get with a file mask:

cd folder
get *test*
like image 158
Martin Prikryl Avatar answered Jan 30 '26 06:01

Martin Prikryl


Are you required to use sftp? A tool like rsync that operates over ssh has flexible include/exclude options. For example:

rsync -a <user>@<server>:folder/ folder/ \
  --include='test_*.txt' --exclude='*.txt'

This requires rsync to be installed on the remote system, but that's very common these days. If rsync isn't available, you could do something similar using tar:

ssh <user>@<server> tar -cf- folder/ | tar -xvf- --wildcards '*/test_*.txt'

This tars up all the files remotely, but then only extracts files matching your target pattern on the receiving side.

like image 42
larsks Avatar answered Jan 30 '26 06:01

larsks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!