簡體   English   中英

Unix shell 代碼。 如何計算文本文件中每一行的字母數

[英]Unix shell code. How to count the number of letters on each line from a text file

我在 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 

遍歷文件所有行的一般模式類似於:

i=0; while read line; do
    printf "Line $((++i)) has %d letters\n" \
      "$(echo "$line" | tr -dc a-zA-Z | wc -c)";
done < input

但是while read...; do... done < input 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM