How do I get only the numbers from a filename in another directory? Using ONLY sed awk or bash? Assume it can be any arbitrary length but the format will always be ABC1234.

If I have a file name ABC1311.crs then I only want 1311.
I've tried:

number=`awk -F '[]' '{print $2}' $data/ABC123.crs

3 Answers 3


This seems like an odd requirement, but to extract digits from arbitrary filenames, you could use parameter expansion to remove anything from the filename that's not a digit:

for f in *
  printf '%s\n' "${f//[![:digit:]]/}"

I would use grep:

grep -Eo '[0-9]+' file.txt
  • sorry I forgot to mention I can only use sed awk and bash
    – bull
    Oct 25, 2020 at 1:15
  • 1
    Why are you restricted to those commands? Is this homework?
    – waltinator
    Oct 25, 2020 at 3:54

You can get the numbers by the following command:

echo * | grep -o '[[:digit:]]*'

You can replace echo * by ls if you like.

If you just want to use awk, then you can do the following:

\ls | awk 'match($0, /[[:digit:]]+/) {print substr($0, RSTART, RLENGTH)}'

\ls will list all the files in your directory but awk will print only the first set of numbers. If you have files with multiple numeric strings (such as 2043x924_fjnndkk.jpg), it will only output 2043.

Use \ls if your ls is aliased to something; otherwise, a plain ls will suffice. In my case, I have aliased ls to ls -s (among other options) and so, always get the size printed which interferes with this command.

  • I can only use sed awk or bash
    – bull
    Oct 25, 2020 at 1:24
  • @kevo885 There is no compelling reason to impose that restriction as far as I can see. A Unix system always has both grep and ls.
    – Kusalananda
    Oct 25, 2020 at 9:32

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.