Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Confused about splitting



Anssi Saari wrote on Sun, Mar 31, 2019 at 12:06:16 +0300:
> foofunc3 () {
> 	if [[ $# -ge 1 ]]
> 	then
> 		if=$1 
> 	else
> 		if=eno1
> 	fi
> 	while read g
> 	do
> 	    if [[ $g =~ $if ]]
> 	    then
> 		first=${=g}
> 		break
> 	    fi
> 	done < /proc/net/dev
> 
> 	echo $first
> 	echo length of first is $#first
> }

Here's another solution:

     1	% () {
     2	    : ${1:=enp2s0}
     3	    local -a net_dev_lines=( "${(@f)"$(</proc/net/dev)"}" )
     4	    local line=${${(M)net_dev_lines:#*$1*}[1]}
     5	    print -r -- $=line
     6	    print -r -- ${#${=line}}
     7	  }
     8	17
     9	% 

Line 2 sets $1 to "enp2s0" if it's not already set.

Line 3 slurps the target file (the «$(<…)») and splits it into lines (the «${(f)}»).

Line 4 greps it (that's the :# and the (M) together) and takes the first result
(that's the outer «${…[1]}» construct).

Line 6 splits it, takes the length of the intermediate array, and prints that.

Cheers,

Daniel



Messages sorted by: Reverse Date, Date, Thread, Author