awk script to return the middle line number

I need an awk script that returns the 1st field of the line in the middle of a file. For example, if a file I have has 6 lines, I want it to return the 1st field on line number 3. If a file has 7 lines, I want the script to return the 1st field on line number 4.

File1:

3 214
4 219
5 226
2 349138
1 349745
0 355906

File2:

3 214
4 219
6 220
5 226
2 349138
1 349745
0 355906

For File1, the script should simply return:

5

For File2, the script should simply return:

5
awk 'NR>FNR&&FNR>=(NR-FNR*2){ print $1; exit }' file1 file1

Ruby(1.9+)

$ ruby -0777 -ne 's=$_.split("\n"); puts (s.size%2==0)? s[(s.size/2)-1]:s[s.size/2] ' file
1 Like

Chubler_XL,

Sorry I'm not sure but maybe I didn't explain it clearly. I will only be doing this on one file at a time. I just listed 2 files as 2 separate examples. I tried using the code you put with one file and nothing showed up on the screen. Pardon my ignorance. Can you clarify?

Thanks!

---------- Post updated at 09:14 PM ---------- Previous update was at 09:12 PM ----------

kurumi,

Thank you for the help, but I would like to keep it in awk or bash if possible.

Yes the awk script requires the same file to be passed into it twice, first pass it to get total records 2nd prints the line.

Shame both your demo files produce the same output:

$ awk 'NR>FNR&&FNR>=(NR-FNR*2){ print $1; exit }' file1 file1
5
 
$ awk 'NR>FNR&&FNR>=(NR-FNR*2){ print $1; exit }' file2 file2
5
1 Like

Try this.

awk '{arr[NR]=$1} END{if(NR%2==0)print arr[NR/2]; else print arr[(NR-1)/2]}' inputfile
1 Like

Oh Ok, I didn't understand that at first. It works! Thank you!

---------- Post updated at 09:50 PM ---------- Previous update was at 09:24 PM ----------

This also worked! Thank you!

Hi jontjioe,

Another with awk:

awk '{nr=NR%2?(NR-1)/2+1:NR/2;a[NR]=$1}END{print a[nr]}' file1

Regards.

1 Like

for i in *;do
lines=`cat $i | wc -l`
line=$(($(($lines/2))+$(($lines%2))))
sed -n "$line{p;}" $i | awk '{print $1}'
done