ファイルをn回コピーしてから.zshrcに関数を作成するには?

ファイルをn回コピーしてから.zshrcに関数を作成するには?

重複する可能性があります。コマンドシェルでファイルをx回繰り返します。そして確かに冗長です。各ファイルにインデックスを挿入しながらファイルを複数回コピーする方法しかし、回答を投稿した人は2017年に最後に目撃され、以下のように拡張子のあるファイル(txtファイルだけでなく)から呼び出すことができるようにzshで関数として使用する方法を知りたいと思います。番号はcpx file.ext nどこにありますか?n作成できるコピーの数。また、ファイル名とファイル拡張子をどのように分離しますか?

これはtxtファイルへの答えです。

#!/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

これを行うより小さな方法はありますか?

私が望むのは:cpx hello.py 3作らなければならないということですhello1.py hello2.py hello3.py

ベストアンサー1

zshでこれを強く実行するより簡単な方法が必要です。通常のshでこれを強く実行するより簡単な方法があります。このスクリプトは過度に複雑で脆弱です(すべてのファイル名に拡張子があり、メッセージを表示せずにファイルを上書きすると仮定します...)。今回のトピックはzshに関するものなので、zshの機能を活用します。

これ履歴とパラメータ拡張修飾子 re基本名と拡張子の間でファイル名を分割するために使用されます。ただし、ファイルでのみ使用可能なので注意してください。する拡張機能があります。

警告:テストされていないコードです。

function cpx {
  if (($# != 2)); then
    cat >&2 <<EOF
Usage: cpx FILENAME N
Make N copies of FILENAME.
EOF
    return 1
  fi
  local n=$2
  if [[ $n != <-> ]]; then
    print -ru2 "cpx: $n: not a number"
    return 1
  fi
  local prefix=$1 suffix= i
  # If there is an extension, put the number before the extension
  if [[ $prefix:t == ?*.* ]]; then
    prefix=$1:r
    suffix=.$1:e
  fi
  # If the part before the number ends with a digit, separate the additional
  # number with a dash.
  if [[ $prefix == *[0-9] ]]; then
    prefix+="-"
  fi
  # Copy foo.bar to foo1.bar, foo2.bar, ...
  for ((i=1; i<=n; i++)); do
    cp -p -i -- $1 $prefix$i$suffix
  done
}

おすすめ記事