matt123
matt123

Reputation: 91

for i in ls - Unix syntax

What is wrong with this?

for i in 'ls | grep '^[A-Z]......$'
do
echo $i
done

If I just use the command ls | grep '^[A-Z]......$ I get the files I want

What am I missing?

Upvotes: 0

Views: 2754

Answers (5)

jlliagre
jlliagre

Reputation: 30843

grep is unnecessary as the shell already do filename expansion:

for file in $(ls [A-Z]??????)
do
  echo $file
done

Note that filenames with embedded spaces and similar would break this loop.

ls can be avoided too fixing the former issue, but a test need then to be added to prevent processing a non existing file when no file match the pattern:

for file in [A-Z]??????
do
 [[ -f "$file" ]] && echo $file
done

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342819

the thing that is "wrong" , is that there is no need to use external ls command to list your files and grep your pattern. Just use the shell.

for file in [A-Z]??????
do
 echo $file
done

Upvotes: 4

Marc van Kempen
Marc van Kempen

Reputation: 556

When you use the backtick: "`" instead of the single quote "'" the output of the program between the backticks will be used as input for the shell, i.e.

for i in `ls | grep '^[A-Z]......$'`;do echo $i;done

Upvotes: 1

Borealid
Borealid

Reputation: 98559

Shouldn't those be backticks?

 for i in `ls | grep blahblahblah`; do echo $i; done

Upvotes: 0

Jokester
Jokester

Reputation: 5617

you mean

for i in `ls | grep '^[A-Z]......$'`;do echo $i;done

? actully this is difference between ` and ' , limited within your shell, and not a regex or OS problem.

Upvotes: 0

Related Questions