Replace all dots in filenames except the extension on Linux

Had a directory full of files with dots in the names and needed them all cleaned up. Something like my.report.final.pdf should become my_report_final.pdf, not my_report_final..pdf or worse. This one-liner does the job: for f in *; do pre="${f%.*}"; suf="${f##*.}"; mv -i -- "$f" "${pre//./_}.${suf}"; done Here’s what each part does. ${f%.*} strips everything from the last dot onwards, giving you the filename without its extension. ${f##*.} grabs just the extension by stripping everything up to and including the final dot. Then ${pre//./_} replaces every dot in the base name with an underscore. ...

Count directories in the current folder with a one-liner

A common question that comes up when you’re first getting comfortable with the command line: how do you count just the directories in your current folder? The quick answer is: ls -1 | wc -l This pipes a one-per-line listing of everything in the current directory into wc -l, which counts lines. Simple enough. But there’s a catch. This counts everything – files, symlinks, hidden items, the lot. If you only want directories, you need to be a bit more selective. ...

Count files in a directory with a one-liner

Another quick command line question: how do you count just the files in a directory, excluding subdirectories and other stuff? The classic answer: ls -l . | egrep -c '^-' This lists everything in long format (ls -l), then counts lines that start with a hyphen – which is how ls marks regular files. Directories show up as d, symlinks as l, and so on, so the regex filters them out. It works, but it’s a bit of a trick and relies on understanding ls output format. A more straightforward approach uses find: ...

'How much memory is actually free?'

I keep forgetting this one, so here it is. vmstat -s -SM | grep "free memory" | awk -F" " '{print$1}' It pipes vmstat output through grep and awk to pull just the number – no units, no labels, just the gigabytes sitting there doing nothing.

Replacing an IP address with sed

Sometimes you need to swap an IP address out of a file. Maybe you are moving a server to a new host, updating a config, or just tired of grepping through logs to find the old address. Whatever the reason, sed makes it trivial. The trick is matching the dotted-decimal pattern. An IP address is four groups of numbers separated by dots, so the regex needs to capture that structure. Here is the one-liner: ...