0

I want to merge all files into one. Here, the last argument is the destination file name. I want to take last argument and then in loop stop before last arguments.

Here code is given that I want to implement:

echo "No. of Argument : $#"
for i in $* - 1
do
   echo $i
   cat $i >> last argument(file)
done

How to achieve that?

4

2 に答える 2

3

POSIX 準拠の方法:

eval last_arg=\$$#
while [ $# -ne 1 ]; do
    echo "$1"
    cat "$1" >> "$last_arg"
    shift
done

ここでevalは、実行される文字列内の読み取り専用パラメーターのみを展開しているため、安全ですeval。を介して位置パラメータの設定を解除したくない場合はshift、カウンターを使用して早期にループから抜け出すことで、それらを反復処理できます。

eval last_arg=\$$#
i=1
for arg in "$@"; do
    echo "$arg"
    cat "$arg" >> "$last_arg"
    i=$((i+1))
    if [ "$i" = "$#" ]; then
        break
    fi
 done
于 2014-11-03T13:41:59.253 に答える
3

使用bash:

fname=${!#}
for a in "${@:1:$# - 1}"
do
    echo "$a"
    cat "$a" >>"$fname"
done

ではbash、スクリプトの最後の引数は${!#}です。そこで、ファイル名を取得します。

bash配列から要素を選択することもできます。簡単な例から始めるには、次のことを観察します。

$ set -- a b c d e f
$ echo "${@}"
a b c d e f
$  echo "${@:2:4}"
b c d e

私たちの場合、最初から最後までの要素を選択したいと考えています。最初は number1です。最後は number$#です。最後を除くすべてを選択します。したがって$# - 1、配列の要素が必要です。したがって、最初から最後までの引数を選択するには、次を使用します。

${@:1:$# - 1}
于 2014-11-02T20:42:38.920 に答える