I'm running a find command that's returning multiple results, but I only need the first result. A bit of googling led me to the "read" command, but I couldn't figure it out, and the man page didn't prove too helpful.
4 Answers
Enter your command (example: ls -l
) then the head
command with a pipe like so:
ls -l | head -1
note: there is documentation on this usage of 'head'
http://schillix.sourceforge.net/man/man1/head.1.html
-n number The first number lines of each input file is
copied to standard output. The number option-
argument must be a positive decimal integer.
-number The number argument is a positive decimal
integer with the same effect as the -n number
option.
Shown here and as mentioned in the comments, this also works depending on your unix-based distribution:
ls -l | head -n 1
-
3
-
-
-
-
1More:
head -n -x
all but the x last lines,tail -n +x
the remainder of the lines, starting at line x - more in the ABS guide referred to in my answer with info onread
.– HannuAug 9, 2014 at 9:14
I like lots of ways to tackle unix problems. Here's some others, assuming that command
is replaced by whatever it is you're actually doing:
command | awk 'NR == 1 {print}'
command | sed -e 1q
TMP=`mktemp tempXXX`; command > ${TMP} ; ed ${TMP} << HERE
1p
HERE
command | split -1 - ; cat xaa ; rm -f x[a-z][a-z]
LINECOUNT=$(command | tee tempfile | wc -l | sed -e 's/ *//g'); \
tail -$((${LINECOUNT} - 1)) tempfile | diff -u - tempfile | grep '^+' | \
grep -v '^+++' | sed -e 's/^+//'
If your output is fixed length records (which may be true; example is for 80 characters of input plus a terminal newline):
command | dd ibs=81 count=1
At one point I worked on installing Unix systems from capacity constrained storage devices (floppy disks). We often had to find imaginative ways to use the limited set of commands that we could include on a 1.44MB floppy :)
You can use the more command to control the amount of text that is shown at a time.
To solve your problem :
Redirect your output to a file you create.
Use For Loop with 1 cycle (counter = 1 , -1 each time). You need to use tokens for search function.
The For Loop will ECHO the first command.
Delete your File.
Store the echo of the FOR Loop in a variable (optional).
I can give some usage definitions if you need it.
How to use read
$ echo -e "1\n2\n3\n4\n5" 1 2 3 4 5 $ echo -e "1\n2\n3\n4\n5" | while read n; do echo "n:$n" ; done n:1 n:2 n:3 n:4 n:5 $
More info on how bash works is available at www.tldp.org in Advanced Bash-Scripting Guide
,
there is one more guide on bash Bash Guide for Beginners
.
$ mycommand > myfile.txt
)ls -l | head -1
- as answered by Jeff Clayton. Pipes are a pseudo file, though you can make them a file, usingmkfifo
.