从 bash 中的 wc 中获取整数

发布于 2024-09-19 17:29:14 字数 407 浏览 5 评论 0原文

有没有办法获取 bash 中 wc 返回的整数?

基本上我想在文件名后面将行号和字数写入屏幕。

输出:文件名行数字数 这是我到目前为止所拥有的:

files=\`ls`
for f in $files;
do
        if [ ! -d $f ] #only print out information about files !directories
        then
                # some way of getting the wc integers into shell variables and then printing them
                echo "$f $lines $words"
        fi
done

Is there a way to get the integer that wc returns in bash?

Basically I want to write the line numbers and word counts to the screen after the file name.

output: filename linecount wordcount
Here is what I have so far:

files=\`ls`
for f in $files;
do
        if [ ! -d $f ] #only print out information about files !directories
        then
                # some way of getting the wc integers into shell variables and then printing them
                echo "$f $lines $words"
        fi
done

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

脱离于你 2024-09-26 17:29:15

只是:

wc -l < file_name

会完成工作。但此输出包含前缀空格,因为 wc 使数字右对齐。

Just:

wc -l < file_name

will do the job. But this output includes prefixed whitespace as wc right-aligns the number.

巾帼英雄 2024-09-26 17:29:15

您可以使用 cut 命令获取第一个wc 输出的单词(即行数或字数):

lines=`wc -l $f | cut -f1 -d' '`
words=`wc -w $f | cut -f1 -d' '`

You can use the cut command to get just the first word of wc's output (which is the line or word count):

lines=`wc -l $f | cut -f1 -d' '`
words=`wc -w $f | cut -f1 -d' '`
望喜 2024-09-26 17:29:15

有时 wc 在不同的平台上以不同的格式输出。例如:

在 OS X 中:

$ echo aa | wc -l

         1

在 Centos 中:

$ echo aa | wc -l

1

因此,仅使用 cut 可能无法检索到号码。相反,尝试 tr 删除空格字符:

$ echo aa | wc -l | tr -d ' '

Sometimes wc outputs in different formats in different platforms. For example:

In OS X:

$ echo aa | wc -l

         1

In Centos:

$ echo aa | wc -l

1

So using only cut may not retrieve the number. Instead try tr to delete space characters:

$ echo aa | wc -l | tr -d ' '
如梦 2024-09-26 17:29:15
wc $file | awk {'print "$4" "$2" "$1"'}

根据您的布局进行必要的调整。

使用正逻辑(“是文件”)比使用负逻辑(“不是目录”)更好

[ -f $file ] && wc $file | awk {'print "$4" "$2" "$1"'}
wc $file | awk {'print "$4" "$2" "$1"'}

Adjust as necessary for your layout.

It's also nicer to use positive logic ("is a file") over negative ("not a directory")

[ -f $file ] && wc $file | awk {'print "$4" "$2" "$1"'}
小姐丶请自重 2024-09-26 17:29:15

已接受/流行的答案不适用于 OSX。

以下任何内容都应该可以在 bsd 和 linux 上移植。

wc -l < "$f" | tr -d ' '

wc -l "$f" | tr -s ' ' | cut -d ' ' -f 2

wc -l "$f" | awk '{print $1}'

The accepted/popular answers do not work on OSX.

Any of the following should be portable on bsd and linux.

wc -l < "$f" | tr -d ' '

OR

wc -l "$f" | tr -s ' ' | cut -d ' ' -f 2

OR

wc -l "$f" | awk '{print $1}'
长伴 2024-09-26 17:29:15

如果将文件名重定向到 wc ,它将在输出中忽略文件名。

Bash:

read lines words characters <<< $(wc < filename)

或者

read lines words characters <<EOF
$(wc < filename)
EOF

不要使用 for 来迭代 ls 的输出,而是这样做:

for f in *

如果文件名包含空格,这将起作用。

如果无法使用通配符,则应该通过管道输入 while read 循环:

find ... | while read -r f

或使用进程替换

while read -r f
do
    something
done < <(find ...)

If you redirect the filename into wc it omits the filename on output.

Bash:

read lines words characters <<< $(wc < filename)

or

read lines words characters <<EOF
$(wc < filename)
EOF

Instead of using for to iterate over the output of ls, do this:

for f in *

which will work if there are filenames that include spaces.

If you can't use globbing, you should pipe into a while read loop:

find ... | while read -r f

or use process substitution

while read -r f
do
    something
done < <(find ...)
霊感 2024-09-26 17:29:15

如果文件很小,您可以调用两次 wc ,并使用类似以下的内容,这可以避免管道进入额外的进程:

lines=$((`wc -l "$f"`))
words=$((`wc -w "$f"`))

$((...))是 bash 的算术扩展。在这种情况下,它会从 wc 的输出中删除所有空格。

如果您需要行数字数,此解决方案更有意义。

If the file is small you can afford calling wc twice, and use something like the following, which avoids piping into an extra process:

lines=$((`wc -l "$f"`))
words=$((`wc -w "$f"`))

The $((...)) is the Arithmetic Expansion of bash. It removes any whitespace from the output of wc in this case.

This solution makes more sense if you need either the linecount or the wordcount.

半透明的墙 2024-09-26 17:29:15

使用sed怎么样?

wc -l /path/to/file.ext | sed 's/ *\([0-9]* \).*/\1/'

How about with sed?

wc -l /path/to/file.ext | sed 's/ *\([0-9]* \).*/\1/'
小…红帽 2024-09-26 17:29:15
typeset -i a=$(wc -l fileName.dat  | xargs echo | cut -d' ' -f1)
typeset -i a=$(wc -l fileName.dat  | xargs echo | cut -d' ' -f1)
剩一世无双 2024-09-26 17:29:15

试试这个数字结果:
nlines=$( wc -l <​​ $myfile )

Try this for numeric result:
nlines=$( wc -l < $myfile )

听风吹 2024-09-26 17:29:15

stackoverflow 上有一个很好的解决方案,其中包含示例 此处

我将在这里复制最简单的解决方案:

FOO="bar"
echo -n "$FOO" | wc -l | bc                     # "3"

也许这些页面应该合并?

There is a great solution with examples on stackoverflow here

I will copy the simplest solution here:

FOO="bar"
echo -n "$FOO" | wc -l | bc                     # "3"

Maybe these pages should be merged?

左秋 2024-09-26 17:29:15

像这样的事情可能会有所帮助:

#!/bin/bash
printf '%-10s %-10s %-10s\n' 'File' 'Lines' 'Words'
for fname in file_name_pattern*; {
    [[ -d $fname ]] && continue
    lines=0
    words=()
    while read -r line; do
        ((lines++))
        words+=($line)
    done < "$fname"
    printf '%-10s %-10s %-10s\n' "$fname" "$lines" "${#words[@]}"
}

Something like this may help:

#!/bin/bash
printf '%-10s %-10s %-10s\n' 'File' 'Lines' 'Words'
for fname in file_name_pattern*; {
    [[ -d $fname ]] && continue
    lines=0
    words=()
    while read -r line; do
        ((lines++))
        words+=($line)
    done < "$fname"
    printf '%-10s %-10s %-10s\n' "$fname" "$lines" "${#words[@]}"
}
∞觅青森が 2024-09-26 17:29:15

要 (1) 运行 wc 一次,并且 (2) 不分配任何多余的变量,请使用

read lines words <<< $(wc < $f | awk '{ print $1, $2 }')

完整代码:

for f in *
do
    if [ ! -d $f ]
    then
        read lines words <<< $(wc < $f | awk '{ print $1, $2 }')
        echo "$f $lines $words"
    fi
done

示例输出:

$ find . -maxdepth 1 -type f -exec wc {} \; # without formatting
 1  2 27 ./CNAME
  21  169 1065 ./LICENSE
 33 130 961 ./README.md
  86  215 2997 ./404.html
  71  168 2579 ./index.html
 21  21 478 ./sitemap.xml

$ # the above code
404.html 86 215
CNAME 1 2
index.html 71 168
LICENSE 21 169
README.md 33 130
sitemap.xml 21 21

To (1) run wc once, and (2) not assign any superfluous variables, use

read lines words <<< $(wc < $f | awk '{ print $1, $2 }')

Full code:

for f in *
do
    if [ ! -d $f ]
    then
        read lines words <<< $(wc < $f | awk '{ print $1, $2 }')
        echo "$f $lines $words"
    fi
done

Example output:

$ find . -maxdepth 1 -type f -exec wc {} \; # without formatting
 1  2 27 ./CNAME
  21  169 1065 ./LICENSE
 33 130 961 ./README.md
  86  215 2997 ./404.html
  71  168 2579 ./index.html
 21  21 478 ./sitemap.xml

$ # the above code
404.html 86 215
CNAME 1 2
index.html 71 168
LICENSE 21 169
README.md 33 130
sitemap.xml 21 21
安静被遗忘 2024-09-26 17:29:15

已回答问题中提出的解决方案不适用于 Darwin 内核。

请考虑以下适用于所有 UNIX 系统的解决方案:

  1. 准确打印文件的行数:
wc -l < file.txt | xargs
  1. 准确打印文件的字符数:
wc -m < file.txt | xargs
  1. 准确打印文件的字节数:
wc -c < file.txt | xargs
  1. 准确打印文件的字数文件:
wc -w < file.txt | xargs

Solutions proposed in the answered question doesn't work for Darwin kernels.

Please, consider following solutions that work for all UNIX systems:

  1. print exactly the number of lines of a file:
wc -l < file.txt | xargs
  1. print exactly the number of characters of a file:
wc -m < file.txt | xargs
  1. print exactly the number of bytes of a file:
wc -c < file.txt | xargs
  1. print exactly the number of words of a file:
wc -w < file.txt | xargs
打小就很酷 2024-09-26 17:29:15

试试这个:

wc `ls` | awk '{ LINE += $1; WC += $2 } END { print "lines: " LINE  " words: " WC }'

它创建行计数和字数(LINE 和 WC),并使用从 wc 中提取的值来增加它们(使用 $1 作为第一列的值,使用 $2 作为第二列的值),最后打印结果。

Try this:

wc `ls` | awk '{ LINE += $1; WC += $2 } END { print "lines: " LINE  " words: " WC }'

It creates a line count, and word count (LINE and WC), and increase them with the values extracted from wc (using $1 for the first column's value and $2 for the second) and finally prints the results.

决绝 2024-09-26 17:29:15

“基本上我想在文件名后面将行号和字数写入屏幕。”

answer=(`wc $f`)
echo -e"${answer[3]}
lines:  ${answer[0]}
words:  ${answer[1]}
bytes:  ${answer[2]}"

输出:
我的文件.txt
线路:10
字数:20
字节:120

"Basically I want to write the line numbers and word counts to the screen after the file name."

answer=(`wc $f`)
echo -e"${answer[3]}
lines:  ${answer[0]}
words:  ${answer[1]}
bytes:  ${answer[2]}"

Outputs :
myfile.txt
lines: 10
words: 20
bytes: 120

我的鱼塘能养鲲 2024-09-26 17:29:15
files=`ls`
echo "$files" | wc -l | perl -pe "s#^\s+##"
files=`ls`
echo "$files" | wc -l | perl -pe "s#^\s+##"
柳絮泡泡 2024-09-26 17:29:15

您必须

number_of_lines=$(wc -l <myfile.txt)

在您的上下文中分别使用 wc: 的输入重定向

echo "$f $(wc -l <"$f") $(wc -w <"$f")"

You have to use input redirection for wc:

number_of_lines=$(wc -l <myfile.txt)

respectively in your context

echo "$f $(wc -l <"$f") $(wc -w <"$f")"
情感失落者 2024-09-26 17:29:14

有史以来最简单的答案:

wc < filename 

Most simple answer ever:

wc < filename 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文