开发者

shell script: while read line No such file or directory

开发者 https://www.devze.com 2023-04-12 09:18 出处:网络
I have a simple problem to resolve.Count number of delimiters for each line in a file. Here is my sample file:

I have a simple problem to resolve. Count number of delimiters for each line in a file.

Here is my sample file:

4489201,6421,,,
4619802,4276

I want to count how many commas in each line. I wrote this while read line script, but keep getting an error "No such file or directory"

#!/bin/bash
data_file="$1"

while read line
do 
    delimiter_cnt=`sed 's/[^,]//g' $line | wc -c`

echo "delimiter_cnt"
done < $data_file

The error message is:

sed: can't read 4489201,6421,,,,,,,,,: No such file or directory
0
sed开发者_如何学Go: can't read 4619802,4276,,,,,,,,,: No such file or directory
0

I would really appreciate your help. Thanks in advance.


You are asking sed to read a file by that name. Try sending your input to sed's stdin:

delimiter_cnt=`echo $line | sed 's/[^,]//g' | wc -c`


use awk:

awk -F, '{print NF-1}' < input_file

By -F, you say awk, to use , as a field separator, and then for each line print NF-1 value. NF is a number of fields in awk for the current record.


I like Michał Šrajer's awk answer. If you use bash, you can do it right in the shell:

while read line; do
    commas=${line//[^,]/}
    echo ${#commas}
done < filename
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号