简体   繁体   中英

read float from a specific line in a file using shell script

I have a series of data files that I need to get a few specific values from. I know the line in the file that the data is on. My data files look like this

x    y    z
1    0.2  0.3
2    0.1  0.2
3    0.5  0.6
etc.

I am using a shell script to access the files, collect the desired data from each file, and output the collected data in one file.

For example, I need the y value in line 3, 0.1. I have tried the following

let dataLine=3
let yVal=`head -n $dataLine dataFile | tail -n 1 | awk '{print $2}'`

but I get the following error

let: yVal=0.1: syntax error: invalid arithmetic operator (error token is ".1")

I have tried adding | bc | bc after awk '{print $2}' but then it did not even register the correct value for what should be assigned to yVal . When I do it as shown above, it does show that it is recognizing the value in the correct line and column.

Thanks for the help,

If you want to get 3rd line's 2nd field then following may help you in same.

Solution 1st: If you want to pass any shell variable's value to any awk variable then following may help you in same.

line_number=3
awk -v line="$line_number" 'FNR==line{print $2}'  Input_file

Solution 2nd: If you want to directly print 3rd line's 2nd field then following may help you in same.

awk 'FNR==3{print $2}'  Input_file
$ dataLine=3
$ yVal=$(awk -v dataLine="$dataLine" 'NR==dataLine{print $2}' data)
$ echo $yVal
0.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM