creating command

Asked by khaled ney

i want to create a command which is list the first few lines of every file in a directory specified by the argument. but i am really stuck with it

Question information

Language:
English Edit question
Status:
Solved
For:
Ubuntu bash Edit question
Assignee:
No assignee Edit question
Solved by:
khaled ney
Solved:
Last query:
Last reply:
Revision history for this message
actionparsnip (andrew-woodhead666) said :
#1

What do you have so far?

Revision history for this message
Midnight Matt (randygaffer) said :
#2

Try this:
ls -a "argument" | grep -v ^'.'$ | grep -v ^'..'$ |
 while read x; do if [[ -f "argument$x" ]]; then
  echo "$x:"
  head -3 "argument$x"
  echo ''
  fi
 done

Replace each instance of the word `argument` with the directory name. The command `ls -a` lists the names of all files, directories, links, etc., including hidden ones, contained in the passed directory name. Its first 2 lines of output are a single period and a double period. These are metacharacters for the argument directory and its parent directory. They must be filtered out with the `grep -v` command to avoid redundant output. Each name is then checked to see if it's a file name and not a directory, soft link, etc.. If that test is satisfied, then the `head -3` command displays the first 3 lines of the file. You can specify any number of lines to display with the argument to the `head` command; the default is 10. A zero-length string is then echoed to create a blank line. The loop exits when each name in the argument has been processed.

Good luck.

Revision history for this message
Midnight Matt (randygaffer) said :
#3

This just in - you can leave off the `grep` commands. Just do this instead.

ls -a "argument" | while read x; do
 if [[ -f "argument$x" ]]; then
  echo "$x:"
  head -3 "argument$x"
  echo ''
  fi
 done

Revision history for this message
khaled ney (k-awad) said :
#4

thx a lot