Dr. Mark Humphrys

School of Computing. Dublin City University.

Online coding site: Ancient Brain

coders   JavaScript worlds

Search:

Free AI exercises


Sample Shell script - filterbaks

  .* files are hidden by convention, by ls and other tools.
We can pipe commands through a program to make other files hidden by convention.

e.g. Hide text editor backup files (things like file%, file~, file.bak):

# make some files ending in % or ~ or .bak 
# then see how we could exclude them from a listing:

  ls -al $* | grep -v "%$" | grep -v "~$" | grep -iv "\.bak$"
 

grep -v means exclude lines that contain the pattern 

$ here means end-of-line
^ means start-of-line
. means any character
\. means the literal character '.'
  

Exercise

The following shows that we want to exclude the exact pattern that matches, no less and no more.
e.g. Don't match '.bak' or 'bak' in middle of filename like: 'airflights.bakuwait.txt'

Work through the following example:

# make 3 files:
$ touch airflights.bakuwait.txt
$ touch airflights.bakuwait.bak
$ touch somebakuwait.data

# list them:
$ ls -l *kuwait*
-rw-r--r-- 1 mhumphrysdculab tutors 0 Feb 21 11:45 airflights.bakuwait.bak
-rw-r--r-- 1 mhumphrysdculab tutors 0 Feb 21 11:44 airflights.bakuwait.txt
-rw-r--r-- 1 mhumphrysdculab tutors 0 Feb 21 11:45 somebakuwait.data

# if we exclude any line with "bak" we exclude everything:
$ ls -l *kuwait* | grep -v 'bak'

# ".bak" also excludes everything! Why?
$ ls -l *kuwait* | grep -v '.bak'

# "\.bak" is better but still not right 
$ ls -l *kuwait* | grep -v '\.bak'
-rw-r--r-- 1 mhumphrysdculab tutors 0 Feb 21 11:45 somebakuwait.data

# "\.bak$" is what we want 
$ ls -l *kuwait* | grep -v '\.bak$'
-rw-r--r-- 1 mhumphrysdculab tutors 0 Feb 21 11:44 airflights.bakuwait.txt
-rw-r--r-- 1 mhumphrysdculab tutors 0 Feb 21 11:45 somebakuwait.data
  

filterbaks

Make our list of grep's into a separate file, called say "filterbaks":

       grep -v "%$" | grep -v "~$" | grep -iv "\.bak$"

so we can reuse it in directory listing:

	ls -al $* | filterbaks

and in other programs:

      if test `echo $i | filterbaks`
      then
       ...
Makes backup files invisible everywhere (until needed).

  

egrep

It would be more efficient to replace 3 programs piped together with 1 program (with more complex arguments).
(Why would this be more efficient?)
We can do this using the "egrep" program, which can grep for boolean expressions.
filterbaks can be rewritten as simply:
	egrep -iv  "%$|~$|\.bak$" 
where, inside the string here,   |   means "OR".



d

Here is a Shell script that I call "d".

ls -l $* | filterbaks

I type "d" to see the files excluding backup files.
I type "ls" to see all the files.



ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.      New 250 G VPS server.

Note: Links on this site to user-generated content like Wikipedia are highlighted in red as possibly unreliable. My view is that such links are highly useful but flawed.