I moved many photos to a folder and needed to list them, but I needed only their numbers. The photos were named as they came out of the camera: IMG_7565.JPG, IMG_7568.JPG, IMG_7571.JPG… I needed just the numbers: 7565, 7568, 7571… They were just 30 photos; I could easily have typed the numbers one by one in a few minutes. But as a good Linux user who knows how powerful this system is, I spent a few minutes searching for a terminal command that could do this for me automatically, accurately, without the risk of typos. I found it and want to share it.
TL;DR: for those in a hurry, here’s the command I used in the photos folder:
1
find . -type f -name "*[0-9]*" | grep -o '[0-9]\+' | sort
How did I come up with that command? That was actually very simple. I already knew the find command, which allows one to search for files in folders. So I searched on Google:
linux find print just the number
The AI overview gave me some command suggestions, including:
To print only numbers from the output of the
findcommand in Linux, you can combinefindwith other tools likegrep,sed, orawk. This allows you to filter or extract numeric values from the file paths or other information provided byfind.1. Extracting numbers from filenames:
If filenames contain numbers and you want to extract them:
1 find . -type f -name "*[0-9]*" | grep -o '[0-9]\+'
find . -type f -name "*[0-9]*": This finds all regular files (-type f) in the current directory and its subdirectories that have at least one digit in their name (-name "*[0-9]*").grep -o '[0-9]\+': This pipes the output offindtogrep. The-ooption tellsgrepto print only the matching parts of the lines, and'[0-9]\+'is a regular expression that matches one or more digits.
That was exactly what I needed. Using the Files app, I opened the folder containing the photos, then I opened that folder in Console (terminal), and ran the command suggested by Google’s AI. The result was almost perfect:
1
2
3
4
5
6
7606
7596
7661
7654
7655
...
I realized the numbers were out of order. Luckily, I also knew the sort command, so I just added a pipe to it, arriving at the complete command I presented at the beginning:
1
find . -type f -name "*[0-9]*" | grep -o '[0-9]\+' | sort
Now the listing is perfect:
1
2
3
4
5
6
7565
7568
7571
7572
7577
...
Linux can be a very powerful system if you know how to use it. Of course, nobody knows everything, just as I didn’t know about the combination of commands I ended up using to solve my problem. But today we have artificial intelligence that can help us discover what we don’t know yet; our limitation nowadays becomes knowing how to ask the right question. Therefore, it’s worthwhile to study, at least minimally, how to use the terminal and its main commands, so we can ask AI great questions and get great answers.
Have you ever solved a problem creatively using scripts or terminal commands? Please, share your story in the comments!