echo '123-321-333-111-235' |
awk -F'-' -v n=3 '
{
for( i=1; i<=n; ++i )
k = k (k == "" ? "" : FS) $i
;
print k
}
'
O loop for
é executado 3 vezes:
i=1:
k is empty, $i -> $1 -> 123
k <= empty ( empty == empty ? empty : "-" ) 123
k <= empty empty 123
k <= "123"
i=2:
k is "123", $i -> $2 -> 321
k <= "123" ( 123 == empty ? empty : "-" ) 321
k <= "123" "-" "321"
k <= "123-321" due to the implicit concatenation property of awk strings
i=3:
k is "123-321", $i -> $3 -> 333
k <= "123-321" ( 123-321 == empty ? empty : "-" ) 333
k <= "123-321" "-" "333"
k <= "123-321-333"
This value of k is now sent to stdout.
STOP.
Como alternativa, você também pode fazer o seguinte:
n=3
echo '123-321-333-111-235' | sed -ne "s/-/\n/$n;P"
echo '123-321-333-111-235' | perl -F- -lane "\$, = '-'; print @F[0..$n-1]"
(
var='123-321-333-111-235'
set -f; IFS='-'; set -- $var
for((i=1;i<=$n;i++))
do
v=${v-}${v:+"$IFS"}$1
done
echo "$v"
# or, alternatively:
N=$#
while case $# in 'expr $N - $n' ) break ;; esac; do
V=${V-}${V:+"$IFS"}$1
shift
done
echo "$V"
)
var='123-321-333-111-235'
FS='-'; # field separator provided here
fields=$(yes "[^$FS]*$FS" | head -n $n | tr -d '\n')
result='expr "$var$FS" : "\($fields\)"'
echo "${result%?}"