【问题标题】:How to get the length of each word in a column without AWK, sed or a loop? [duplicate]如何在没有 AWK、sed 或循环的情况下获取列中每个单词的长度? [复制]
【发布时间】:2016-08-12 04:31:20
【问题描述】:

有可能吗?我目前有一个单行来计算文件中的单词数。如果我输出我目前拥有的内容,它看起来像这样:

3 abcdef
3 abcd
3 fec
2 abc

这一切都是在没有循环的 1 行中完成的,我在想是否可以在列中添加一个包含每个单词长度的列。我在想我可以使用wc -m 来计算字符数,但我不知道我是否可以在没有循环的情况下做到这一点?

如标题所示,没有 AWK、sed、perl.. 只是好的旧 bash。

我想要什么:

3 abcdef 6
3 abcd 4
3 fec 3
2 abc 3

最后一列是每个单词的长度。

【问题讨论】:

  • 想到expr length WORD 只使用内置的shell 而没有调用wc
  • wc -m 也算\n

标签: bash


【解决方案1】:
while read -r num word; do
    printf '%s %s %s\n' "$num" "$word" "${#word}"
done < file

【讨论】:

  • 我比我更喜欢这个解决方案。它更优雅。
  • 虽然awk '{print $1, $2, length($2)} file' 会运行得更快。
  • @RanyAlbegWein 这不适用于带空格的输入:1 hello world -> 1 hello 5 但应该是 1 hello world 11
  • @andlrc 如果 OP 想要这种行为,可以很容易地修复。从这个问题中,我了解到他/她要求的是单个字长。感谢您强调这一点。
【解决方案2】:

你也可以这样做:

文件

> cat test.txt

3 abcdef
3 abcd
3 fec
2 abc

Bash 脚本

> cat test.txt.sh

#!/bin/bash

while read line; do
  items=($line) # split the line
  strlen=${#items[1]} # get the 2nd item's length
  echo $line $strlen # print the line and the length
done < test.txt

结果

> bash test.txt.sh

3 abcdef 6
3 abcd 4
3 fec 3
2 abc 3

【讨论】:

    猜你喜欢
    • 2017-12-06
    • 2019-07-31
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    相关资源
    最近更新 更多