每当我运行这个脚本时都有一个问题。它得到了文件的正确字数,但是每当我在终端中运行它时,它都有不必要的空格。
#!/bin/bash
char=$(cat $1 | wc -c)
echo "This file has $char characters in it."
nolines=$(cat $1 | tr -d "n" | wc -c)
echo "This file has $nolines characters not counting the new line."
emptyline=$(grep -cv 'S' $1) echo "This file has $emptyline empty lines."
alphachar=$(tr -cd '[:alpha:]' < $1 | wc -c)
echo "This file has $alphachar alphanumeric characters."
使用包含this的名为example_file
的文件(这是this下的文件,或文件的内容):
This is the first line
This is the second
This has the symbols @#$
there was just an empty line.
所以每当我运行~/script.sh example_file
这样的脚本时它都会输出
This file has 93 characters in it.
This file has 88 characters not counting the new line.
This file has 1 empty lines.
This file has 70 alphanumeric characters.
我期望输出之间没有空格。
是的,wc
(有时)允许在数字结果前写空格。
考虑以下在MacOS上看到的行为:
$ /usr/bin/wc -c <<<"hello" | xxd
00000000: 2020 2020 2020 2036 0a 6.
这些20
都是空格(0a
是尾随的换行符,36
是数字6);它们在那里是因为wc
的POSIX标准指定-c
禁止打印数字,除了请求的(字节计数)数字;但是它不会禁止打印空格。
这个版本的wc
的行为违反了当前版本的POSIX标准,该标准规定,当没有文件名作为参数传递给wc
时,前导空格应该被抑制;当前的GNU coretilswc
不像问题描述的那样运行。
无论如何,要关闭它,只需使用参数展开(如${char//[[:space:]]/}
)或算术上下文($((char))
:
char=$(wc -c <"$1")
echo "This file has $((char)) characters in it."