You are not logged in.

#1 2011-12-20 19:40:37

oliver
Member
Registered: 2007-12-12
Posts: 448

[solved] useless use of cat question

I'm trying to clean up some ksh scripts I inherited and found this:

for f in `cat file | grep -v ^#`
do
  ...
done

How would I do this without cat?  I've been playing around with the following to no avail:

while read f
do
  ...
done<"grep -v ^# file"

Everything works in the scripts... it's just for my own amusement

Last edited by oliver (2011-12-20 19:56:05)

Offline

#2 2011-12-20 19:45:15

aiBo
Member
Registered: 2010-11-10
Posts: 50

Re: [solved] useless use of cat question

this should do:

for f in $(grep -v ^# file)
do
... 
done

Offline

#3 2011-12-20 19:45:40

knopwob
Member
From: Hannover, Germany
Registered: 2010-01-30
Posts: 239
Website

Re: [solved] useless use of cat question

i don't know if this will work in ksh, but in bash you could do this:

grep -v '^#' file |
while read f; do
     .....
done

edit:

actually, my solution will behave differently..
In my solution $f will contain a whole line on each iteration while in your old version with cat $f will contain only one word each iteration. This wouldn't matter, of course, if each line only contains one word.

Last edited by knopwob (2011-12-20 19:52:29)

Offline

#4 2011-12-20 19:55:26

oliver
Member
Registered: 2007-12-12
Posts: 448

Re: [solved] useless use of cat question

thank you both... regarding the whole line versus one word I can play around with IFS to get around that.

I'll mark this badboy as solved

Offline

#5 2011-12-20 20:02:59

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: [solved] useless use of cat question

Hey, wait for me!

#!/bin/bash
while read f
do
  echo $f
done < <(grep -v ^# file)

Offline

#6 2011-12-20 20:29:09

oliver
Member
Registered: 2007-12-12
Posts: 448

Re: [solved] useless use of cat question

karol wrote:

Hey, wait for me!

#!/bin/bash
while read f
do
  echo $f
done < <(grep -v ^# file)

can you explain why the second <  is needed?

Offline

#7 2011-12-20 20:48:21

alphaniner
Member
From: Ancapistan
Registered: 2010-07-12
Posts: 2,810

Re: [solved] useless use of cat question

The <(...) is process substitution, the lone < is the more familiar redirection.  Essentially, it's like doing:

#!/bin/bash
grep -v "^#" file > file2
while read f
do
  echo $f
done < file2

In other words, the output of the process in parenthesis is treated as a file from which read pulls its STDIN.

Last edited by alphaniner (2011-12-20 20:51:33)


But whether the Constitution really be one thing, or another, this much is certain - that it has either authorized such a government as we have had, or has been powerless to prevent it. In either case, it is unfit to exist.
-Lysander Spooner

Offline

#8 2011-12-20 20:49:08

oliver
Member
Registered: 2007-12-12
Posts: 448

Re: [solved] useless use of cat question

very nice...  thanks again to all

Offline

Board footer

Powered by FluxBB