当前位置: 动力学知识库 > 问答 > 编程问答 >

shell - Read count of parameter passed to user variable in UNIX

问题描述:

I have a requirement.

I am accepting an USER input in a variable using UNIX(ksh) script.

file_name='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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: