3

I have in a directory /home/files/ some files that all have the same extension .txt.

For example

1.txt
2.txt
3.txt
4.txt
5.txt
test.txt

These files are all the same in data format but the data are different. All these files have at least the following line inside

frames=[number here]

This line appears multiple times in a file so i need to get the value of frames= that appears last in the file.

And as i stated i want to get that line, from all the above files that match the extension .txt in a directory (no need for recursive).

Is there any single bash command to do that?

EDIT

Expected output:

1.txt=5000
2.txt=123
3.txt=3452
4.txt=111
5.txt=958
test.txt=1231
2

With find + grep:

find . -name '*.txt' -exec sh -c 'grep -HPo "frames=\K.*" "$0" | tail -n1' {} \;

And with shell for loop + grep in similar fashion:

for file in *.txt; do grep -HPo 'frames=\K.*' "$file" | tail -n1; done
2

Using gawk and provided that there will only be one = on the line, you can do:

gawk -F= 'ENDFILE { print FILENAME"="$2 }' *.txt

Update

Just realised I misread this question, I thought the line you were looking for was always be the last line. To use the last line that starts with frames=, for gawk do:

gawk -F= '/^frames=/ { frames=$2 } ENDFILE { print FILENAME"="frames }' *.txt

Or with any awk:

for file in *.txt; do
  awk -F= '/^frames=/ { frames=$2 } END { print FILENAME"="frames }' "$file"
done
  • no the problem is that it has many = inside the file but i only want the frames= value :( – OhGodWhy Jan 11 '15 at 11:25
  • @BlackDream, updated – Graeme Jan 11 '15 at 11:49
2

You can do it with awk

awk -F= '/^frame/{line=FILENAME "=" $2}NR!=1 && FNR==1{print line}END{print line}' *.txt

Or with sed (GNU version more than 4.2.2)

sed -sn '/^frame/{s///;h};${F;x;p}' *.txt | sed 'N;s/\n//'
  • @mikeserv Please extend your offer re F in sed (example?). I add bash as extra (main is awk) and I am not sure that is a slowest but may be longest. – Costas Jan 11 '15 at 13:29
1

With pax (probably also most any tar) and tr and GNU sed:

pax -w ./*txt | 
tr -s \\0     | 
sed -nz '/txt$/h
         /\n*.*frames\(=[0-9]*\).*\n/!d
    H;x;s//\1/p'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.