2017-03-15 85 views
0

我想使用bash重命名/更新/home/cmccabe/Desktop/percent中的文本文件的文件名,基於數字與/home/cmccabe/Desktop/analysis.txt中的另一個文本文件的部分匹配。匹配將始終位於此文件的第3,4或5行。我無法做到這一點,但希望下面的'bash'是一個開始。謝謝 :)。在bash更新目錄中的文件名基於部分匹配到另一個

文本文件/home/cmccabe/Desktop/percent - 有可能是一個最大的3個文件在此目錄

00-0000_fbn1_20xcoverage.txt 

文本文件在/home/cmccabe/Desktop/analysis.txt

status: complete 
id names: 
00-0000_Last-First 
01-0101_LastN-FirstN 
02-0202_La-Fi 

所需的結果/home/cmccabe/Desktop/percent

00-0000_Last-First_fbn1_20xcoverage.txt 

慶典

for filename in /home/cmccabe/Desktop/percent/*.txt; do echo mv \"$filename\" \"${filename//[0-9]-[0-9]/}\"; done < /home/cmccabe/Desktop/analysis.txt 

回答

1

使用適當Process-Substitution語法與while-loop

您可以在/home/cmccabe/Desktop/percent

#!/bin/bash 
#  ^^^^ needed for associative array 

# declare the associative array 
declare -A mapArray 

# Read the file from the 3rd line of the file and create a hash-map 
# as mapArray[00-0000]=00-0000_Last-First and so on. 

while IFS= read -r line; do 
    mapArray["${line%_*}"]="$line" 
done < <(tail -n +3 /home/cmccabe/Desktop/analysis.txt) 

# Once the hash-map is constructed, rename the text file accordingly. 
# echo the file and the name to be renamed before invoking the 'mv' 
# command   

for file in *.txt; do 
    echo "$file" ${mapArray["${file%%_*}"]}"_${file#*_}" 
    # mv "$file" ${mapArray["${file%%_*}"]}"_${file#*_}" 

done 
+0

謝謝兩位非常:)。 – Chris

+0

該解決方案是一種移植「awk」代碼以破解代碼! –

1

這又是一個類似bash的方式運行腳本:

while IFS="_" read -r id newname;do 
#echo "id=$newid - newname=$newname" #for cross check 
oldfilename=$(find . -name "${id}*.txt" -printf %f) 
[ -n "$oldfilename" ] && echo mv \"$oldfilename\" \"${id}_${newname}_${oldfilename#*_}\"; 
done < <(tail -n+3 analysis) 

我們讀到的分析文件,我們使用_作爲分隔符的每一行(即00-0000_Last優先)拆分兩個字段:
ID = 00-000
NEWNAME =後進先

然後使用我們從文件「分析」中讀取的這個文件ID,我們檢查(使用find)來查看是否存在以相同ID開始的文件。
如果存在這樣的文件,它的文件名將返回到變量$ oldfilename中。
如果這個變量不是空的,那麼我們做mv。
尾-n + 3用於忽略前三行的文件RESULTS.TXT

Test this solution online here

相關問題