Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first line of a file in a bash script?

Tags:

bash

I have to put in a bash variable the first line of a file. I guess it is with the grep command, but it is any way to restrict the number of lines?

like image 674
Neuquino Avatar asked Mar 13 '10 18:03

Neuquino


People also ask

How do I show the first line of a text file?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file.

What is the first line in a bash script?

The bash first line in script begins with a shebang (#!). These are two mandatory characters, after which is indicated which program you are using for scripting. Now it is bin / bash, but other programs use this mechanism. If you did not specify the program, bash will be used by default.


2 Answers

head takes the first lines from a file, and the -n parameter can be used to specify how many lines should be extracted:

line=$(head -n 1 filename)
like image 83
sth Avatar answered Oct 07 '22 08:10

sth


to read first line using bash, use read statement. eg

read -r firstline<file

firstline will be your variable (No need to assign to another)

like image 81
ghostdog74 Avatar answered Oct 07 '22 08:10

ghostdog74