【原创】bash实用: 拷贝nce英语听力

【原创】bash实用: 拷贝nce英语听力

曾经喜欢拿新概念英语(nce)来练听力
拷到mp3中没事就听

我的习惯是一篇课文听上几十遍
而不是拷几十篇从头到尾听一遍

以前系统没足够人性化/傻瓜化时
往mp3设备里拷文件总是费劲

mount -> copy -> umount
特别是我要将一篇听力合成10遍的
得需要运行个for f in {1..10} ...

反正我挺懒
写了个小脚本来完成拷贝
脚本里要拷贝的每个文件都会重复10次
合成一个大的文件
这样在mp3里听时每篇听力都会放10次 ( 10 in 1 )
但可以很方便地跳到下一首

以前写得很乱
仓促改了改加了简单注释就贴上来了:)


注意一下我硬盘里的听力文件格式为 lessonXY.mp3

[php]
[0 No.2053 huan@huan ~/svn_bash/running]$ cat mynce.sh
#! /bin/bash
# set -n
# set -x

# where to copy to
dst="/media/usb"

# where to copy from
src="/home/huan/study/nce3/"

# default device to copy to
dev=/dev/sda1

# run as root to use mount/umount, not a good idea
if (( $(id -u) != 0 )); then
        sudo $0 "$@"
        exit $?
fi

copy(){
        for file in $*;do
                if [[ ! -f $src/lesson${file}.mp3 ]];then
                        echo "Can not find \"$src/lesson${file}.mp3\", skipped."
                        continue
                fi
                if [[ -f  $dst/lesson${file}.mp3 ]];then
                        rm  $dst/lesson${file}.mp3
                fi
        # copy each files ten times
                for((i=1;i<=10;i++))do
                        cat $src/lesson${file}.mp3 >> $dst/lesson${file}.mp3
                done
        done
        #echo "Done."
}

usage(){
    echo "$(basename $0) [ -d device ] [ files_to_copy ]"
    exit 0
}

if [[ $1 == '-d' ]]; then
    shift
    dev="$1"
    shift
elif [[ $1 == "-h" ]] || [[ $1 == "--help" ]];then
    usage
fi

# check if it's a block dev
if [[ ! -b $dev ]]; then
    echo "$dev not a block device"
    exit 1
fi

# if not mounted, try to mount
if ! mount | fgrep -q "$dev" ;then
    [[ -d $dst ]] || mkdir $dst
        if      ! mount $dev $dst -o iocharset=utf8; then
        echo "Can not mount $dev --> $dst, aborting ..."
        rmdir $dst
            exit 127
        fi
# mounted, get the mountpoint
else
    dst=$( mount | fgrep "$dev" | awk '{ print $3 }')
fi

rm $dst/lesson* 2> /dev/null

if [[ $1 == '' ]];then
    # ask what to copy
        read -p "lesson[s] to copy: " LESSON
        echo "This will take a little time, please be patient ..."
        copy $LESSON
else
        copy $@
fi

# umount device after copying
if umount $dst 2>/dev/null;then
        echo "Done"
else
    echo "$dst busy now, will be umounted if the device not used any more ..."
    umount -l $dst
fi

[/php]


使用示例
复制内容到剪贴板
代码:
#直接输入要拷几些课
[0 No.2058 huan@huan ~/svn_bash/running]$ mynce 35 36
Done

# 交互输入
[0 No.2059 huan@huan ~/svn_bash/running]$ mynce
lesson[s] to copy: 35 36
This will take a little time, please be patient ...
Done

# 指定 mp3 设备
[0 No.2060 huan@huan ~/svn_bash/running]$ mynce -d /dev/sda1 35 36
Done

[0 No.2061 huan@huan ~/svn_bash/running]$ mynce -h
mynce [ -d device ] [ files_to_copy ]

[0 No.2062 huan@huan ~/svn_bash/running]$
      
不错, 可惜俺没有 MP3