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
done
To use it, let's call this script refactor_text.sh
:
refactor_text.sh 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 refactor_text.sh.
Snippets
#! /bin/sh
#
# refactor_text.sh
# Copyright (C) 2018 [Anselmos](github.com/anselmos) <anselmos@users.noreply.github.com>
#
# Distributed under terms of the MIT license.
#
for i in $(ack2 -l "$1"); do
sed -i -e "s/$1/$2/g" $i
done
refactor_text.sh some_ugly_name_for_variable some_prettier_variable
Acknowledgements
Auto-promotion
Related links
- BASH Programming - Introduction HOW-TO: Loops for, while and until
- shell script - Using 'sed' to find and replace - Unix & Linux Stack Exchange
- Changing Variable Names in Vim - Stack Overflow
- shell script - Using 'sed' to find and replace - Unix & Linux Stack Exchange
- Examples of How the Linux Sed Command Is Used
Thanks!
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
comments powered by Disqus