2016-05-29 1310 views
0

我在我的服務器中包含一些PDF文件的文件夾。我的問題是,我必須複製到其他服務器並重命名它。Shell腳本複製(scp)並重命名

名稱格式是這樣的「yymmdd_hhmmss_FileNo_PdfNo.pdf」

yymmdd_hhmmss_001_AC1.pdf 
yymmdd_hhmmss_001_AC2.pdf 
yymmdd_hhmmss_002_AC1.pdf 
yymmdd_hhmmss_003_RCY1.pdf 

而複製這些文件,我要重命名每個文件。 名稱格式是這樣的 「FileNo_PdfNo_yymmddhhmmss.pdf」

001_AC1_yymmddhhmmss.pdf 
001_AC2_yymmddhhmmss.pdf 
002_AC1_yymmddhhmmss.pdf 
003_RCY1_yymmddhhmmss.pdf 

我想寫這個shell腳本(bash)的。請給我一些想法或與此相關的一些示例腳本。

+0

'SCP SOURCE_NAME用戶@遠程主機:dest_name' – anishsane

+0

或者,如果你願意,你可以'scp'整個目錄&然後'SSH用戶@遠程主機女士prename ...'命令 – anishsane

+0

它總是好的添加你所擁有的到目前爲止。請參閱[\ [mcve \]](http://stackoverflow.com/help/mcve) – sjsam

回答

1

有了一些細微的調整這應該爲你工作。我將解釋/評論放在腳本中。你可能會在沒有循環的情況下做到這一點,但是同時使用scp傳輸和重命名多個文件會非常棘手。如果您將它們重命名爲本地,然後轉移它們,則可以輕鬆完成單個scp調用。你也可以把它凝聚成一個班輪;但我認爲這種方法可能更容易解釋,也更容易修改。

#!/bin/bash - 

# associative array to hold new file names 
declare -A new; 

# local and remote paths terminated with/for laziness 
local_path="/lcl/path/to/pdfs/" 
remote_path="/remote/path/to/pdfs/" 

# [email protected] for remote ssh connection 
user_mach="[email protected]" 

# error accumulator 
local lcl_err=0 

# Collect list of files to send - you may want this to be 
# more discriminating 
orig=`find "$local_path" -name "*.pdf" -exec basename {} \;` 

# Iterate through the file list 
for i in "${orig[@]}"; do 
    # sed replacement to rename them appropriately, stored in 
    # associative array new 
    new["$i"]="`echo $i | sed -ne 's/^\([0-9]\{6,\}\)_\([0-9]\{6,\}\)_\([0-9]\{3,\}\)_\(.*\)\.pdf$/\3_\4_\1\2\.pdf/p'`" 

    # if file was renamed (passed regex filter) then scp it to remote host, 
    # saving it remotely with new name 
    if [ ${new["$i"]} ]; then 
    scp "${local_path}$i" "${user_mach}:${remote_path}${new["$i"]}" 
    # don't roll over the return value (256 == 0 in 8 bit return value) 
    [[ "$lcl_err" -lt "255" ]] && ((lcl_err+=$?)) 
    else 
    echo "Skipping file $i" 
    fi 
done 
exit "$lcl_err"