List the files after sorting based on file content

Hi,

I have two pipe separated files as below:

head -3 file1.txt
"HD"|"Nov 11 2016  4:08AM"|"0000000018"
"DT"|"240350264"|"56432"
"DT"|"240350264"|"56432"
head -3 file2.txt
"HD"|"Nov 15 2016  2:18AM"|"0000000019"
"DT"|"240350264"|"56432"
"DT"|"240350264"|"56432"

I want to list the files based on increasing order of column 3 in first line.
(Column 3 is the file version, and I need to list them in increasing order)

I am able to get the file version using below command:

for FILE_NAME in `ls *txt`
do 
    FILE_VERSION=$(awk -F'|' '$1=="\"HD\""{gsub(/"/,"",$3);print $3}' $FILE_NAME)
echo $FILE_NAME $FILE_VERSION
done

Output:

file1.txt 0000000018
file2.txt 0000000019

Is there a way to sort this and list?

P.S. Once I get the list, I will loop the files one by one for processing

How about

awk -F'|' '$1=="\"HD\"" {gsub(/"/,"",$3); print FILENAME, $3}' *.txt | sort -k2
1 Like

how about this ?

same code of @Rudic.. but just adding exit to read only the first line on all files

for file in *.txt; do awk -F'|' '$1=="\"HD\"" {gsub(/"/,"",$3); print FILENAME, $3;exit}' ${file}; done | sort -k2
1 Like

Thanks, It gives below output:

file2.txt 0000000018
file1.txt 0000000019

So I just taking the first field alone:
for file in *.txt; do awk -F'|' '$1=="\"HD\"" {gsub(/"/,"",$3); print FILENAME, $3;exit}' ${file}; done | sort -k2 | awk '{print $1}'

Now, please help me how to loop with this. I need to open the files and do processing with it.

I'd be VERY surprised if any of the proposals yielded THAT output.

In using the output for a loop, where are you stuck?

I got it:

myarray=`for file in *.txt; do awk -F'|' '$1=="\"HD\"" {gsub(/"/,"",$3); print FILENAME, $3;exit}' ${file}; done | sort -k2 | awk '{print $1}'`
for i in ${myarray[@]}
 do
 echo $i
done

OK, should work. How about

awk -F'|' '$1=="\"HD\"" {gsub(/"/,"",$3); print FILENAME, $3}' *.txt | sort -k2 | while read FN DUMMY; do echo "$FN"; done