1837983 Members
2962 Online
110124 Solutions
New Discussion

Read

 
Vanquish
Occasional Advisor

Read

Hi
I need to read the first line of the file and the last line of the file.
can i use head or tail for doing that?
Thanks
7 REPLIES 7
Dave La Mar
Honored Contributor

Re: Read

Certainly.
head -1 your_file > some_new_file
tail -1 your_file >> some_new_file

Best regards,

dl
"I'm not dumb. I just have a command of thoroughly useless information."
A. Clay Stephenson
Acclaimed Contributor

Re: Read

The tail command can be used for both but if all you want to do is read the 1st line of a file, the line command is perfect

INFILE=myfile
FIRST=$(line < ${INFILE})
LAST=$(tail -n -1 ${INFILE})

echo "First: ${FIRST}"
echo "Last : ${LAST}"
If it ain't broke, I can fix that.
Rodney Hills
Honored Contributor

Re: Read

You could use the sed command.

set -A data `sed -ne '1p;$p' echo First line is ${data[0]}
echo Last line is ${data[1]}

HTH

-- Rod Hills
There be dragons...
Rodney Hills
Honored Contributor

Re: Read

Oh, be sure to put the following in the script before the "sed"-

IFS="^J"

^J is what you get when you press control-v followed by CR.

HTH

-- Rod Hills
There be dragons...
Thom Cornwell
Frequent Advisor

Re: Read

sed -n '1p;$p' input-file-name
Hein van den Heuvel
Honored Contributor

Re: Read


I like the sed solutions.

Here is a simple awk solution in case you need to do more then just print:

awk 'BEGIN {getline; print} END {print x} {x=$0}' < your-file


And a silly solution in perl:

$ perl -e 'while (<>) {print unless ($x); $x=$_} print $x' < your-file

- loop through the input, print the line uless you have remembered a line. This takes care of the first line. Remembering lines in $x. At the end, print the last line remembered... being the last line :-).

KapilRaj
Honored Contributor

Re: Read

echo "`head -1 yourfile` "\\n" `tail -1 yourfile` "

regds,

Kaps
Nothing is impossible