[英]Unix shell code. How to count the number of letters on each line from a text file
I have the following code in Linux shell file: I need to replace the "..." with the number of letters of the coresponding line.我在 Linux shell 文件中有以下代码:我需要将“...”替换为对应行的字母数。
#!/bin/sh
echo "Filename is: $1\n"
nr_lines=$(wc -l <$1)
echo "Number of lines in files is: $nr_lines\n"
for line in $(seq 1 $nr_lines);
do
echo "Line $line has ... letters"
done
The general pattern for iterating over all lines of a file is something like:遍历文件所有行的一般模式类似于:
i=0; while read line; do
printf "Line $((++i)) has %d letters\n" \
"$(echo "$line" | tr -dc a-zA-Z | wc -c)";
done < input
but using while read...; do... done < input
但是
while read...; do... done < input
while read...; do... done < input
in a shell is often better done with awk: while read...; do... done < input
通常最好使用 awk 完成:
awk '{gsub("[^a-zA-Z]", ""); printf "Line %d has %d letters\n", NR, length}' input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.