Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with choosing a file 1

Status
Not open for further replies.

mzak94

Programmer
Nov 23, 2013
1
0
0
GB
i need a command that lists the first few lines of files, i want to list the files first and then ask for a file to view

so far i have

#! /bin/bash

cd $1

ls

if [ "$(ls -A $1)" ]; then
read -p "show first few lines of files [y/n] " show
if [[ $show == [y] ]]; then
head -3 *
fi
else
echo "$1 is Empty"
fi

exit

can anyone helpme with my arguments
 
What is not working with your script ?
Anyway, I'd replace this:
if [ "$(ls -A $1)" ]; then
with this:
if [ "$(ls)" ]; then

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Hi mzak94 I have recreated your script and it worked for me (on RHEL 5.3).

Are you getting any error messages that could help?

There is only one suggestion I would make in the script and one possible problem I can think of...

Suggestion: Instead of
Code:
if [ "$(ls -A $1)" ]; then
use
Code:
if [ "$(ls -A)" ]; then
as you have already "cd"'d to the directory you want to list.

Possible Problem: If you have too many files in the directory the "*" asterix will not be able to cope. As a solution to this you could use the find command with exec. i.e.:
Code:
find . -type f -maxdepth 1 -exec head -3 {} \;
but you wont get the pretty headers with file names. To get the headers you could do:
Code:
find . -type f -maxdepth 1 | awk '{printf "/n==> "$0" <==/n"; CMD="head -3 "$0; while ( CMD | getline OUT ) { print OUT } ; close(CMD)}'
but its a bit more complex a command :)
 
KierenH, a simpler way:
Code:
find . -type f -maxdepth 1 | xargs head -3

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top