我有两个问题:
1) 我想从我的脚本中删除每个非英语字母 2)我想计算文本的长度,清除标点符号,空格等。我只是不知道这部分有什么问题
Linux 脚本:
#!/usr/bin/bash
awk '
BEGIN { FS="" } # defining a field separator in order to treat each character one by one
{
$0 = tolower($0) # removing case distinctions
gsub(/[[:punct:]]/,"", $0) # removing every punctuation mark
gsub(/\ /, "", $0) # removing spaces
gsub(/[0-9]/, "", $0) # removing digits
gsub(/![a-z]/, "", $0) # removing every non-English letter <- This does not work
#After the removing of every possible punctuation mark, space, digit and non-English
#letter in the user-defined text, we calculate the occurence of each character and place into an array
for (i = 1; i <= NF; i++)
{
freq[$i]++
length++
}
}
但它显示了以下错误: awk:命令。第 17 行:长度++ awk:命令。第 17 行:^ 意外的换行符或字符串结尾
请至少帮我解决第二个问题。我只是不知道有什么问题,一切看起来都很好。预先感谢!
最佳答案
使用awk
awk '{gsub("[^A-Za-z]", "");i+=length}END{print i}'
tr -C -d "A-Za-z" | wc -c
它们都删除 A-Za-z
范围内的所有字符,然后计算剩余的字符。 tr
其优点或缺点取决于您的语言环境。
您还可以创建 awk
脚本的方式与创建 shell 脚本的方式相同。
#!/usr/bin/awk
{ gsub("[^A-Za-z]", ""); i+=length }
END { print i }
为了获得最大的可移植性,您需要将脚本中的区域设置设置为 POSIX
,或者列出每个字符。
tr -C -d "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | wc -c
关于linux - 计算 UNIX 中文本的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788240/