2014-08-27 51 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 

它应该是适用于大部分分布和可能比普通的循环速度上的优势,如果你处理大量的文件。虽然速度不是原来问题的一部分...