I have a directory that contains files with names,

00004.time, 00010.time, ...

There is not pattern except the format,

<5 decimal digits>.time

I would like to output to a file, just the numbers in ascending order. How can I do this from the command line or with script?


In the bash shell, you can remove a 'dot extension' (shortest trailing pattern matching a period followed by any number of characters) from a variable that contains a file name using parameter expansion e.g. if f=00004.time then ${f%.*} evaluates to 00004.

Putting that in a loop over a shell glob,

for f in *.time; do printf '%s\n' "${f%.*}"; done

The order will be determined by the glob (*.time) expansion, and will be the default collation order for your locale - which should be numeric ascending for the input you show. To send the results to a file, use shell redirection

for f in *.time; do printf '%s\n' "${f%.*}"; done > somefile

If you really want to remove the last 5 characters instead of the (more general) dot extension, you can modify that to

for f in *.time; do printf '%s\n' "${f%?????}"; done > somefile
  • Don't embed variables into printf's format string. If it happens to contain any % or \ characters, it will fail or give unintended output. Use printf '%s\n' "${f%.*}" instead of printf "${f%.*}\n". – geirha May 2 '15 at 18:22

In addition to steeldriver's answer, as the substring to be excluded is same for all files, you can use substitution operation of the bash's parameter expansion:

for file in *.time; do echo "${file/.time/}"; done | sort -n > file.txt

This will replace .time with empty string i.e. .time is excluded from the file names.

The syntax for substitution operation is


This will substitute only the first occurrence of OLD with NEW, if you want all occurrence of OLD to be replaced with NEW:


So you just want numbers, and do not want .time part. My two cents here:

ls /path/to/*.time | cut -d '.' -f1  > toSomeFile.txt

Do the same by combination of and basename commands as follows:

find /path/to/dir -name '*.time' -exec basename {} .time \; > someFile

The basename {} .time, strips the ".time" suffix from fileNames.
The {} represent the current found fileName.

Your Answer

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