0

Is it even possible? I currently have a one-liner to count the number of words in a file. If I output what I currently have it looks like this:

3 abcdef
3 abcd
3 fec
2 abc

This is all done in 1 line without loops and I was thinking if I could add a column with length of each word in a column. I was thinking I could use wc -m to count the characters, but I don't know if I can do that without a loop?

As seen in the title, no AWK, sed, perl.. Just good old bash.

What I want:

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

Where the last column is length of each word.

mythic
  • 895
  • 2
  • 13
  • 31

2 Answers2

3
while read -r num word; do
    printf '%s %s %s\n' "$num" "$word" "${#word}"
done < file
Rany Albeg Wein
  • 3,304
  • 3
  • 16
  • 26
3

You can do something like this also:

File

> cat test.txt

3 abcdef
3 abcd
3 fec
2 abc

Bash script

> 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

Results

> bash test.txt.sh

3 abcdef 6
3 abcd 4
3 fec 3
2 abc 3
zedfoxus
  • 35,121
  • 5
  • 64
  • 63