甚至可能吗?我目前有一个单行计算文件中的单词数。如果我输出我现在拥有的东西,它看起来像这样:
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
最后一列是每个单词的长度。
答案 0 :(得分:3)
while read -r num word; do
printf '%s %s %s\n' "$num" "$word" "${#word}"
done < file
答案 1 :(得分:3)
您也可以这样做:
文件强>
> 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