How do I distribute row entries per line in UNIX, run commands on each row and return the output immediately?

advertisements

I am trying to do something very simple, but solving it the way I want would help me with many other commands as well.

I want to read a file line by line in UNIX and perform commands on them, in this case character count. For an entire file, I would just use:

wc -m

However, I want this per line of input. What is the simplest, shortest way to stream a file line by line for manipulation by UNIX commands? I ask because in this situation I want wc -m per line, but future applications will use completely different commands.

Also, I want to avoid perl and awk! I already know how to do this with those tools, but am looking for alternate methods.

Thanks!

EDIT: Thanks for the link to the other question, but after looking at their 4 answers, I don't see a solution to my exact quandary.

Given the following input:

cat test.txt
    This is the first line.
    This is the second, longer line.
    This is short.
    My Final line that is much longer than the first couple of lines.

I want to plug it through some code that will read it line by line and perform a command on each line, immediately returning the result.

Some code which does wc -m on each line and returns the output:

23
32
14
65

Or some code which does cut -d " " -f 1 on each line and returns the output:

This
This
This
My

Hopefully this makes things a bit clearer. Thanks again for any suggestions!


You can use echo "${#line}" to know the length of a string. Reading the file with a while read... will do the rest:

$ cat file
hello
my name
is fedor
qui

$ while read line; do echo "${#line}"; done < file
5
7
8
3
0

In a nicer format:

while read line
do
   echo "${#line}"
done < file