DEV Community

Kishi
Kishi

Posted on

Useful UNIX one-liner

Some of you have probably used UNIX commands without even realizing it. Windows has its old DOS commands, but UNIX commands are on another level. They’re designed to do one thing, and do it well. On top of that, they’re modular and compact, thanks to the pipe operator (|), you can chain commands together and build powerful workflows out of simple parts.

These are some useful UNIX commands I find useful for everyday tasks.

1) Remove string from filenames

Say you are working in a sort of creative department, and you are given images that may have filenames like images_2135435431322.jpeg. Now, it would not be a good look or produce an impressionable impression on someone's else perception.

You can quickly clean up filenames using this Unix one-liner:

for file in *.jpeg; do
mv "$file" "$(echo "$file" | sed 's/[0-9]\+//g')"
done

This loops over all .jpeg files in the current directory, and remove all numbers from the filename.

2) Count files by type

Say you want to quickly want to check how many images, logs or documents you have without opening a GUI, this is how you would do it:

ls *.png | wc -l

This lists all PNG files, and count the number of that files. Here, you can replace .png with different file format.

3) Find the largest file

Say your folder is big, and you want to locate huge files, and might possibly want to delete it to clean up the disk.

du -sh * | sort -hr | head -5

This shows the size of each file in human-readable format, sort the largest file, and show the top 5 largest files/folders.

This is mainly good for quick checkups in your project folder. On Windows (e.g., Git Bash / MINGW64), the du command doesn’t support all Linux-style options like -h (human-readable) and -s (summary) in the same way, so the output might look different than on Linux. So you might want to use -k show the size of each file/folder in kilobytes.

4) Batch rename extensions

Say you want to convert all .jpeg files to .jpg for consistency:

for file in *.jpeg; do
mv "$file" "${file%.jpeg}.jpg"
done

This is the same as number 1 before, except that this strips the .jpeg extension.
This is perfect for standardizing filenames in folders.

5) Search for a string in all project files

Say you write a helper function, and import it into different scripts. You want to locate which scripts are using this helper function or has this particulate function either for renaming it or understanding how it interacts with other parts of the code.

Instead of opening every file manually, you can run:

grep -rn "showErrorMessage" .

This can tell you where the function is defined, and used, and it helps you debug, refactor codes, etc.

Top comments (0)