各ファイルにインデックスを挿入しながらファイルを複数回コピーする方法

各ファイルにインデックスを挿入しながらファイルを複数回コピーする方法

ascdrgi.txt次の内容を含むファイルがあります。

tiger
lion
cat

ファイル名の最後の文字を変更して(拡張子を無視)、このファイルを(可変)回数だけ繰り返したいと思います。たとえば、この場合、3つのコピーを作成すると、名前は次のようになります。

  • ascdrgj.txt
  • ascdrgk.txt
  • ascdrgl.txt

ファイル名が数字で終わる場合は、その数字を増やす必要があるため、コピーは次のascdrg1.txtようになります。

  • ascdrg2.txt
  • ascdrg3.txt
  • ascdrg4.txt

ファイルがすでに存在する場合、スクリプトはその名前をスキップして次の名前に移動する必要があります。最後の文字(、、または)に達した場合は、z最初Z9繰り返す必要があります(次の文字はそれぞれaAまたはです1)。

元のファイルのコピーに加えて、各ファイルの最初の行を変更して、そのファイルが何であるか(数字)とファイルの総数を知らせる必要があります。最初のascdrgi.txt例では、ファイルに次のものが含まれます。

tiger number(1,4)
lion
cat

次のファイルには以下がascdrgj.txt含まれます。

tiger number(2,4)
lion
cat

など。

ベストアンサー1

次のシェルスクリプトは、必要なほとんどのタスクを実行します。元のファイルは変更されず(「番号」は追加されません)、新しく作成されたファイルのみが変更されます。

コメントが十分に明確であることを願っています。 bashの引数拡張の代わりにやや複雑なアプローチを使用すると、expr移植性が向上します。

#!/bin/sh

orig=ascdrg3.txt # start with this file

in=$orig
count=1 #loop variable
max=5   #number of files to create
while test "$count" -le "$max" ; do
    # Remove extension
    base=$(basename "$in" .txt)

    # get the prefix
    prefix=$(expr substr "$base" 1 $((${#base}-1)))

    # get last letter
    last=$(expr substr "$base" ${#base} 1)

    while true ;
    do
        # Advance letter, while the file doesn't exist
        last=$(echo "$last" | tr A-Z B-ZA)
        last=$(echo "$last" | tr a-z b-za)
        last=$(echo "$last" | tr 0-9 1-90)

        # construct new file name
        new="$prefix$last.txt"

        # continue if it doesn't exist
        # (otherwise, advance the last letter and try again)
        test -e "$new" || break

        test "$new" = "$orig" \
            && { echo "error: looped back to original file" >&2 ; exit 1; }
    done


    # Create new file
    cp "$orig" "$new"

    # Modify first line of new file
    sed -i "1s/\$/number($count,$max)/" "$new"

    # Advance counter
    count=$((count+1))

    # loop again
    in=$new
done

おすすめ記事