Date Tags sed / ack2

Today let's check how to use SED tool that can be used for text replacement.

To The Point

You can replace text in files using sed

sed -i -e 's/few/asd/g' file.ext

We can also make use of ack2 for searching and combine it with sed to create a simplier script than making each call to each individual file.

Let's first find out if ack2 will give as an output list of files in which it will find searched phrase. Using ack2 --help we find out, that -l flag gives us a list of files with seached phrase.

We can now combine those two using only bash script with for-loop.

Let's loop each found file from ack2 and then pass the file path to sed which will replace searched phrase with replacement phrase.

This can then be used as a similar functionality to refactoring name in pycharm (take into consideration it will replace in all files if finds so it's not a full-time replacement for pycharm).

Our script will look like this:

for i in $(ack2 -l "$1"); do
    sed -i -e "s/$1/$2/g" $i

To use it, let's call this script some_ugly_name_for_variable some_prettier_variable

Which will look for some_ulgy_name_for_variable in all files from directory you are executing script and replace it with some_prettier_variable in those files which content matches searching phrase.

I've added it into my linux-utils repository as a


#! /bin/sh
# Copyright (C) 2018 [Anselmos]( <>
# Distributed under terms of the MIT license.

for i in $(ack2 -l "$1"); do
    sed -i -e "s/$1/$2/g" $i
done some_ugly_name_for_variable some_prettier_variable



Related links


That's it :) Comment, share or don't - up to you.

Any suggestions what I should blog about? Post me a comment in the box below or poke me at Twitter: @anselmos88.

See you in the next episode! Cheers!


comments powered by Disqus