Shell脚本:从远程读取文件

使用shell脚本,

如何从另一个服务器(user@192.168.10.x:/ home / admin / data)读取文件并将其存储在“files”数组中? (第四行代码)

1 reportTypes=(0001 0102 8902) 2 3 # collect all files matching expression into an array 4 files=(Rep_[0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-1].csv) 5 6 # take only the first hundred 7 files=( "${files[@]:0:100}" ) 8 9 shopt -s nullglob # allow a glob to expand to zero arguments 10 11 # echo ${files[@]} 12 13 for i in ${reportTypes[@]}; do 14 printf -v val '%04d' "$i" 15 groupFiles=( $( for j in ${files[@]} ; do echo $j ; done | grep ${val} ) ) 16 17 # Generate sequence file for EACH Report Type 18 forqlift create --file="Report${val}.seq" "${groupFiles[@]}" 19 done 

编辑:

我试着用第四行replace:

 while IFS= read -rd '' file; do files+=( "$file" ) done < <(ssh user@host "cd /home/admin/data && printf '%s\0' Rep_[0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-1].csv") 

但是当我要生成hadoop序列文件(使用forqlift,第18行),它失败。

 ERROR forqlift.ui.Driver - java.io.FileNotFoundException: Rep_0001_20150102_0.csv (No such file or directory) 

所以现在重写这个答案,这个问题的一些含糊之处已经被清除了。

您希望将文件(匹配模式)从远程主机复制到本地主机,然后对其进行迭代。 然后使用scp(或rsync)来下载它们,然后在本地进行迭代。

 # this copies the matching filenames from the remote host to the current dir. The quotes are important. scp "user@host:/home/admin/data/Rep_[0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-1].csv" ./ # Now that the files are accessible locally, you may iterate them with a for-loop for file in Rep_[0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-1].csv; do printf 'Do something with %s\n' "$file" done 

好吧,现在我将我的答案更改为一个工作脚本:

 declare -a ARRAY count=0; for F in $(ssh localhost find ./ -name "\*.sh" | xargs basename -a) ; do ARRAY[$count]=$F ((count++)) done ELEMENTS=${#ARRAY[@]} for (( i=0;i<$ELEMENTS;i++)); do echo ${ARRAY[${i}]} done 

您正在搜索的文件(在此脚本* .sh中)将被保存到名为ARRAY的bash数组中。

这个测试,它的工作。

 user@user-virtual-machine:~$ ./filenames2array.sh user@localhosts password: deleteme1.sh deleteme9.sh deleteme2.sh deleteme7.sh deleteme8.sh deleteme10.sh deleteme4.sh deleteme3.sh deleteme5.sh filenames2array.sh deleteme6.sh user@user-virtual-machine:~$ 

这个被写入通过SSH连接到本地主机。 您可以将本地主机更改为您想要的任何远程服务器。