adamkdean

software engineering

Count occurrences with grep

By Adam K Dean on

Today I learnt that grep has a '-c' switch that counts occurrences. I'll never pipe it to 'wc -l' again!

$ ps aux | grep -c adam
93

But if we use wc, we would also need to trim it:

$ ps aux | grep adam | wc -l
        94

So, use -c.

RegEx match all words with a prefix

By Adam K Dean on

Here is a snippet to match all words that begin with a specified prefix.

/\bprefix\S+/g

JavaScript implementation:

"test tbl_test1 tbl_test2 test".match(/\btbl_\S+/g)

Or

/\btbl_\S+/g.exec("test tbl_test1 tbl_test2 test")

Which is the same as:

var regex = /\btbl_\S+/g;
    matches = [],
    match;

while (match = regex.exec(line)) {
    matches.push(match[0]);
}

If you want a dynamic prefix, use RegExp:

var regex = new RegExp('\\b' + prefix + '\\S+', 'g'),
    matches = [],
    match;

while (match = regex.exec(line)) {
    matches.push(match[0]);
}

Remove branch from remote git repo

By Adam K Dean on

To remove a branch from a remote git repository, you have to push an empty branch.

$ git push origin :branch-name
- [deleted]        branch-name

If you want to also remove it from the local repo, delete the branch:

$ git checkout master 
Switch to branch 'master'

$ git branch -D branch-name
Deleted branch branch-name (was abcd123)

We change branch as you can't delete the branch you're on.

Fleetctl destroy all services

By Adam K Dean on

Here is a nice little bash trick to destroy all services using fleetctl.

fleetctl list-units | sed 1d | while read -r line ; \
    do fleetctl destroy $(echo $line | cut -f1 -d ' '); done

It gets a list of units, removes the first line, loops through, grabs the first word, and and destroys it.

$ fleetctl list-units | sed 1d | while read -r line ; \
    do fleetctl destroy $(echo $line | cut -f1 -d ' '); done
Destroyed Job august-frosting_v4.web.1-announce.service
Destroyed Job august-frosting_v4.web.1-log.service
Destroyed Job august-frosting_v4.web.1.service
Destroyed Job august-frosting_v4.web.2-announce.service
Destroyed Job august-frosting_v4.web.2-log.service
Destroyed Job august-frosting_v4.web.2.service
Destroyed Job quaint-teamwork_v5.cmd.1-announce.service
Destroyed Job quaint-teamwork_v5.cmd.1-log.service
Destroyed Job quaint-teamwork_v5.cmd.1.service
Destroyed Job quaint-teamwork_v5.cmd.2-announce.service
Destroyed Job quaint-teamwork_v5.cmd.2-log.service
Destroyed Job quaint-teamwork_v5.cmd.2.service

Now imagine typing each of those by hand.

Detect if JS is running under Node

By Adam K Dean on

Here is a snippet for how to detect if JavaScript is running under Node:

var isNode = typeof process !== "undefined" && 
    {}.toString.call(process) === "[object process]";

We check here whether the variable process is defined, and if it is, we check it's type to make sure it's the proper process object and not just a regular old JavaScript object.