0

I found (on Google) this perfectly working line to replace every occurences in all files in my directory and subdirectories:

grep -lr previoustext | xargs sed -i 's/previoustext/newtext/g'

It works great.

But now I'm trying to use it in a function in my bash_aliases file as following:

freplace() {
    grep -lr previoustext | xargs sed -i 's/previoustext/newtext/g';
}

However, when I call

freplace previoustext newtext

in my terminal, nothing happens ... . The text is not replaced.

Any idea why it doesn't work ?

AdminBee
  • 22,803
Zkyem
  • 3
  • Welcome to the site. Please note that the command you use can be a problem if you have filenames that contain special characters (like whitespace), because that can lead to unwanted word splitting (see this question for reasons). If you have the GNU version of the tools installed, it is advisable to use the -Z option of grep together with the -0 option of xargs to prevent this kind of problems. – AdminBee Aug 12 '20 at 10:16
  • ~/bash_alaises is not a standard file. Are you perhaps using Ubuntu? That's the only system I know of that includes that file by default. What is the output of grep bash_aliases ~/.bashrc? More importantly, is that the exact function? Do you already have the strings previoustext and newtext hardcoded in the function? If so, why are you also passing them to your function as arguments? – terdon Aug 12 '20 at 10:18

1 Answers1

2

If you want to pass arguments to a function, you need to use positional parameters to pick them up.

freplace() {
    grep -lr "$1" | xargs sed -i "s/$1/$2/g"
}

Note that it doesn't work for strings containing / or other characters special to sed.

choroba
  • 47,233
  • 1
    You could mention that the limitation about / can in part be circumvented by using one of the other separator characters (@,#, ...) - well knowing that of course, these can then also not go unescaped. – AdminBee Aug 12 '20 at 10:12
  • I just forgot to close and reopen the terminal ... thanks, it worked well with the positionnal parameters. – Zkyem Aug 12 '20 at 10:21