1834753 Members
3017 Online
110070 Solutions
New Discussion

list file

 
SOLVED
Go to solution
haeman
Frequent Advisor

list file

for file in `ls /tmp/*.txt`

do
xxx

done


I have the above script to list all *.txt in /tmp then do xxx , if I want to list all *.txt but exclude aaa.txt , can advise what can i do ?

thx
5 REPLIES 5
Patrick Wallek
Honored Contributor

Re: list file

Just add a grep to your ls.

for file in $(ls /tmp/*.txt | grep -v aaa.txt)
do
xxx
done

NOTE -- Notice I used $() around the command rather than that back-ticks (backwards apostrophe, whatever..) symbols. This makes for easier reading and provides that EXACT same functionality.
Hein van den Heuvel
Honored Contributor
Solution

Re: list file

Well, your basic choice is to try to make sure the 'aaa' do not make it into the do - done list, or to make sure that the action within the block is conditional on the file not being called 'aaa'.

I'm sure that the 'aaa' is just an example.
The 'best' solution depends on how complex that 'aaa' really is. Is it just one piece of string?

Example of the method 1:

for file in `ls *.tmp | grep -v aaa`
do
echo --- $file ---
done

Example for method 2:

for file in $(ls *.tmp)
do
if [[ $file != aaa.tmp ]] ; then echo --- $file --- ; fi
done

Example of a perl solution:

$ perl -e 'foreach (<*.tmp>) { next if /aaa/; print qq(--- $_ ---\n)}'

Same presented as 'program' vs one-liner above:

foreach (<*.tmp>) {
next if /aaa/;
print qq(--- $_ ---\n);
}

Regards,
Hein.


haeman
Frequent Advisor

Re: list file

it works , thx
Peter Nikitka
Honored Contributor

Re: list file

Hi,

there are extended filename pattern in ksh, which should be available in HP's Posix shell as well - look at my examples:

ef3nip00@forth ls *.txt
aaa.txt aaab.txt comp_list.txt serial.txt
# Just skip aaa.txt
ef3nip00@forth ls !(aaa).txt
aaab.txt comp_list.txt serial.txt
# skip aaa*.txt
ef3nip00@forth ls !(aaa*).txt
comp_list.txt serial.txt

So for your code:
for file in !(aaa).txt
do print action $file
done

A more general solution would be an analyze of the name in the loop itself:
for file in *.txt
do
case $file in
aaa.txt) continue;;
...
esac
print action $file
done

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Rasheed Tamton
Honored Contributor

Re: list file

If you need just one action, this also can be tried:

ls /tmp/!(aaa.)txt|xargs -i xxx {} {}.bak

Below xxx(your action is replaced by the copy command - hence all the txt files except aaa.txt will be copied with an extension of .bak)

ls /tmp/!(aaa.)txt|xargs -i cp {} {}.bak

Is not time, to start assigning points. Your profile shows you have not started assigning points.

Rgds.