1

Say I have

File1:

Aaron
Vernon
Troy
Roy

File2:

Jason
Derek
Mariano
Alex

I want to display:

File1: Aaron
File2: Alex

What would be a single line bash command that could do both?

I was thinking of using sort and then tail -1, but that only extracts it from 1 file at a time.

3
  • 1
    Do you sometimes go by kylo?
    – Jeff Schaller
    May 29, 2016 at 18:00
  • Haha yes, this question is a tad bit different though.
    – Kylo Ren
    May 29, 2016 at 18:17
  • 1
    grep -H . File1 | sort | head -n 1; grep -H . File2 | sort | head -n 1
    – Cyrus
    May 29, 2016 at 20:58

4 Answers 4

1

With GNU awk (which has a built in array sorting function asort) you could do

gawk '
  BEGINFILE{delete a}; 
  {a[FNR]=$0}; 
  ENDFILE{asort(a); print FILENAME": "a[1];}
' File1 File2
File1: Aaron
File2: Alex

You can write it in a single line if you wish

gawk 'BEGINFILE{delete a}; {a[FNR]=$0}; ENDFILE{asort(a); print FILENAME": "a[1];}' File1 File2
1
for f in File* ; do
  printf "%s: %s\n" "$f" $(sort "$f" | head -n 1)
done

Output:

File1: Aaron
File2: Alex
0

This appears to achieve your goal.

grep . File1 File2|sort -k 2,2 -t:|sed 's/:/: /g'
File1: Aaron
File2: Alex
File2: Derek
File2: Jason
File2: Mariano
File1: Roy
File1: Troy
File1: Vernon
1
  • Thanks a lot! Just what I needed. Out of curiosity how does sed work with those parameters?
    – Kylo Ren
    May 29, 2016 at 19:19
0

For the original question (one line from each file, not all lines sorted as you now say you 'needed'), and efficient if the files are large (especially larger than fits in memory), if you have non-ancient GNU awk (most Linuxes and some other systems with bash):

[g]awk -vx= 'FNR==1||$0<x {x=$0""} ENDFILE {print FILENAME": "x}' file1 file2 ...

With non-GNU awk (or ancient gawk) you can still do it but it's a little clumsier:

[*]awk -vx= 'FNR==1&&NR!=1 {print f": "x} FNR==1||$0<x {f=FILENAME;x=$0""} END {if(NR) print f": "x}' file1 file2 ...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .