2014-08-27 29 views
0

我已經下載了幾個epub文件,我需要再次將它們轉換爲epub,以便我的電子書閱讀器可以讀取它們。在linux bash中使用正則表達式來更改輸出文件名

我可以相當容易地如下使用R請勿轉換在批:

setwd('~/Downloads/pubmed') 
epub.files = list.files('./',full.names = TRUE,pattern = 'epub$') 
for (loop in (1:length(epub.files))) { 
    command = paste('ebook-convert ', 
        epub.files[loop], 
        gsub('\\.epub','.mod.epub',epub.files[loop])) 
    system(command) 
} 

但我不知道如何使用Linux的bash做到這一點,我不知道:1)如何分配for循環中的變量,以及ii)如何使用正則表達式來替換bash中的字符串。

任何人都可以幫忙嗎?謝謝。

回答

0

您可以使用findsed

cd ~/Downloads/pubmed 
for f in $(find . -regex .*epub\$); do 
    ebook-convert $f $(echo $f | sed 's/\.epub/.mod.epub/') 
done 
0

不知道電子書,轉換是什麼,但如果你想重命名這些文件,嘗試以下。將它粘貼到擴展名爲.sh的文件中(以表示一個shell腳本)並確保它是可執行文件(chmod + x your-file.sh)。

#!/bin/bash 
FILES=~/Downloads/pubmed/*.epub 
for f in $FILES 
do 
    # $f stores the current file name, =~ is the regex operator 
    # only rename non-modified epub files 
    if [[ ! "$f" =~ \.mod\.epub$ ]] 
    then 
    echo "Processing $f file..." 
    # take action on each file 
    mv $f "${f%.*}".mod.epub 
    fi 
done 

對於正則表達式支持,您將需要bash版本3或更高版本。這也可以用正則表達式來實現。

0

您可以結合使用GNU parallel與find:

find ~/Downloads/pubmed -name '*.epub' | parallel --gnu ebook-convert {} {.}.mod.epub 

它應該是適用於大部分分佈和可能比普通的循環速度上的優勢,如果你處理大量的文件。雖然速度不是原來問題的一部分...

相關問題