1757867 Members
2852 Online
108866 Solutions
New Discussion юеВ

While Loop Question?

 
SOLVED
Go to solution
Allanm
Super Advisor

While Loop Question?

I have a file which has the following data -

emailid1 word1 word2 word3
emailid2 word1 word3

The spaces between the words are tab separated spaces.

I want to echo each word on the line separately and at the same time consider the next line as a new line.

Please help!
24 REPLIES 24
Michael Steele_2
Honored Contributor
Solution

Re: While Loop Question?

cat file | while read a b c
do
echo $a $b $c
done
Support Fatherhood - Stop Family Law
Allanm
Super Advisor

Re: While Loop Question?

Thanks Micheal!

There is one more piece to it, the words can be more than 3 and the count cannot be predicted. I need a more dynamic way.

Allanm
Super Advisor

Re: While Loop Question?

And dont want to print blank lines.
James R. Ferguson
Acclaimed Contributor

Re: While Loop Question?

Hi Allan:

while read LINE
do
echo ${LINE}|tr -cs "[:alpha:]" "[\012*]"
done < file

Spaces and/or tabs can separate the words in the file.

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: While Loop Question?

Hi (again) Allan:

> And dont want to print blank lines.

OK, so use:

# cat ./lister
#!/usr/bin/sh
while read LINE
do
[ -z "${LINE}" ] && continue
echo "${LINE}"|tr -cs "[:alpha:]" "[\012*]"
done < $1

...run as:

# ./lister file

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: While Loop Question?

Hi (again):

In keeping with TIMTOWDI here's another way:

# perl -nle 'next if m/^\s*$/;print join "\n",split' file

Regards!

...JRF...
Allanm
Super Advisor

Re: While Loop Question?

Thanks JRF!

But this doesn't do what I want to achieve -

Email-ids are of the pattern foo_bar@foobar.com and it is the first entry on each line.I want to print that as is and add a certain html tags around it -



and for the words like words1... I need word1
word2
...

The final document should look like the following -



word1
words2
words3




word1
words3

Dennis Handly
Acclaimed Contributor

Re: While Loop Question?

>I want to echo each word on the line separately

for word in $(< file); do
echo $word
done
Hein van den Heuvel
Honored Contributor

Re: While Loop Question?

Hmm,

Seems like your original problem statement can be satisfied with a simple:

$ tr "\t" "\n" < tmp.txt

look:

$ cat tmp.txt
asergfewgfwegfew aap noot mies
blah more data
$ od -c tmp.txt
0000000 a s e r g f e w g f w e g f e w
0000020 \t a a p \t n o o t \t m i e s \n b
0000040 l a h \t m o r e \t d a t a \n

$ tr "\t" "\n" < tmp.txt
asergfewgfwegfew
aap
noot
mies
blah
more
data

But that's not really what you want apparently, and it looses the 'specialness' of the first word. Why not do it all in one perl one-line or program?


$ perl -ne 'chomp; @words=split; $u=shift @words; print "\n\n"; for (@words) {print "$_<
/word>\n"}; print "
\n
\n"' tmp.txt


aap
noot
mies




more
data



Enjoy!
Hein