0

I've got a temp file made with mktemp. Before the script exits, I must ouput the contents of the file to the screen. The contents have to be lexicographically sorted. When I try to apply sort to the temp file, it outputs a sorted result multiple times. i.e. My temp file looks like this without sorting

OUT="$(mktemp)"
#Add lines to $OUT
cat "$OUT"

This outputs

../a1q2/hello1.cc
../a1q2/hello2.cpp
../a1q2/hello3.h
../a1q2/hello4.C
../a1q2/z/hi.cc
../a1q2/dir/two.cpp
../a1q2/dir/one.cc
../a1q2/dir/three.h
../a1q2/dir/four.C
../extra/dir/hi.cpp
../extra/dir/hi2.C
../extra/hi.cc
../extra/h2.cc
../extra/h3.h

I'd like to sort this lexicographically, but when I do

OUT="$(mktemp)"
#Add some lines to $OUT ...
sort "$OUT"
cat "$OUT"

I get the following output

../a1q2/dir/four.C
../a1q2/dir/one.cc
../a1q2/dir/three.h
../a1q2/dir/two.cpp
../a1q2/hello1.cc
../a1q2/hello2.cpp
../a1q2/hello3.h
../a1q2/hello4.C
../a1q2/z/hi.cc
../extra/dir/hi.cpp
../extra/dir/hi2.C
../extra/h2.cc
../extra/h3.h
../extra/hi.cc
../a1q2/hello1.cc
../a1q2/hello2.cpp
../a1q2/hello3.h
../a1q2/hello4.C
../a1q2/z/hi.cc
../a1q2/dir/two.cpp
../a1q2/dir/one.cc
../a1q2/dir/three.h
../a1q2/dir/four.C
../extra/dir/hi.cpp
../extra/dir/hi2.C
../extra/hi.cc
../extra/h2.cc
../extra/h3.h

I don't know why this is happening. Any help at all would be appreciated

Many Questions
  • 125
  • 1
  • 10

2 Answers2

1

sort outputs to STDOUT, it does not overwrite the file you sorted.

You probably meant to do something like:

sort "$OUT" > sorted.txt
cat sorted.txt
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
0

You can combine two steps with tee, sorted output will be written to a file and to STDOUT.

$ sort file | tee sorted_file
karakfa
  • 66,216
  • 7
  • 41
  • 56