1

I'm writing a script that would allow me to view the content of every file in an entire selected directory but I don't quite know how to do it.

I was thinking about piping the output of ls into cat or less but that doesn't seem to work.

Is there a command line variable I need to use or are there commands that will satisfy my need?

I want this so I can take a quick peak at the contents of files whenever I'm looking for a certain file I can't remember.

5

This is exactly what cat is for. If you want to display the content of all files in your directory, use

cat *

The shell will expand * to the list of files. If you want to include hidden files as well, use

cat * .*

or

shopt -s dotglob; cat *

However, if you just want to quickly identify a file, this might not be the best idea, especially if the files are long.

Using head might help in this case:

head *

will display the first ten lines of each file in the directory, with a heading line giving the name of the file.

| improve this answer | |
  • awesome! thank you so much! i didnt know that arg was available. and ill keep that in mind for the future, right now most of my files are about 10 lines or less – Animal91 Apr 4 '17 at 17:25
0

See "Why *not* parse `ls`?" for why parsing the output of ls may not be a good approach.

For your script:

#!/bin/sh

dir="$1"
PAGER="${PAGER:-cat}"

test -d "$dir" || exit 1

find "$dir" -type f -exec "$PAGER" {} \;

This will take the first command line argument and assign it to the variable dir. The variable PAGER will be set to cat if the user hasn't already set it to something else.

If the given directory is a valid directory name, find is used to pass all regular files (including hidden regular files) in the directory, or any of its subdirectories, to the pager.

To limit the search of files to only the first level of the given directory, insert -maxdepth 1 before the -exec option to find.

Using it:

  • cat all files in /tmp:

    $ ./script /tmp
    
  • See the first 10 lines of all files in your home directory:

    $ PAGER=head ./script "$HOME"
    
  • Read all stories in your ~/stories directory:

    $ PAGER=less ./script "$HOME/stories"
    

Extension:

#!/bin/sh

dir="$1"
suf="$2"
PAGER="${PAGER:-cat}"

test -d "$dir" || exit 1

find "$dir" -type f -name "*$suf" -exec "$PAGER" {} \;

This will allow the script to take an additional filename suffix like

$ ./script /tmp .txt
| improve this answer | |
  • thank you! that's the direction my script was going but not so eloquent. – Animal91 Apr 6 '17 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.