I have a requirement.
I am accepting an USER input in a variable using UNIX(ksh) script.
file_na开发者_Python百科me='po_header*.dat ; po_line*.dat ; po_dist*.dat'
When I echo,
echo "Data File Names : " $file_name
I will get all the file names available at the location. The output will be like given below:
po_headers_057.dat
po_headers_123.dat po_headers_890.dat po_lines_057.dat po_lines_123.dat po_lines_890.dat po_distribution_057.dat po_distribution_123.dat po_distribution_890.dat
I need to get the count of file names passed to the variable separated with ';'. Here in this case 3. i.e, 'po_header*.dat ; po_line*.dat ; po_dist*.dat'
How do I do that?
In ksh
without using any external utilities:
saveIFS=$IFS; IFS=';'; a=($file_name); IFS=$saveIFS; echo ${#a[@]}
As a bonus, your filespecs are now in an array:
$ echo ${a[1]}
po_line*.dat
count=`echo "po_header*.dat ; po_line*.dat ; po_dist*.dat" | \
sed 's/;//g' |wc -w|awk '{print $1;}'`
echo $count
works for po_header*.dat ; po_line*.dat ; po_dist*.dat
, for po_header*.dat ;; po_line*.dat ; po_dist*.dat;
, and for "po_header[0-9].dat ; po_line*.dat ; po_dist*.dat".
An alternative of sed
is to use tr ";" " "
.
one way:
count=$(echo "$file_name" | awk -F';' '{print NF}')
echo $count
Edited - removed $NF -> NF
IFS=\; read -A a <<< "$file_name"; print ${#a[*]}
This sends the content of $file_name to the read command as its standard input, with IFS set to ; for the read (and only the read, so no need to save/reset it). -A tells read to split the input on IFS and save each word in the named array (a). ${#a[*]} gives the number of elements saved.
精彩评论