使用shell脚本,
如何从其他服务器(user@192.168.10.x:/ home / admin / data)读取文件并将其存储在“files”数组中? (第4行代码)
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
编辑:
我尝试用以下代码替换第4行:
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)
答案 0 :(得分:3)
所以现在重写这个答案,这个问题的一些含糊之处已被清除。
您希望将匹配模式的文件从远程主机复制到localhost,然后迭代它们。然后使用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
答案 1 :(得分:-3)
好的,现在我将答案改为工作脚本:
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连接到localhost。您可以将localhost更改为您想要的任何远程服务器。