I try to replace many files at once with sed using * as filename. However it tries to process directories too, and gives error and terminates. Is there a simple way to overcome this?
2 Answers
I'm not sure exactly how you're using sed
here but the normal way to process only regular files in UNIX is with the find
command, something like:
find . -type f -exec sed 's/Hello/Goodbye/g' {} ';'
The type restricts you to regular files, not directories or FIFOs or any other sort of filesystem magic.
If you run man find
on your system, you will see a plethora of other options you can use.
-
1I'm still pretty new to linux/unix shell commands, why is it that when I run this it spams my screen with the contents of many files but never changes anything? Aug 10, 2017 at 15:33
-
1@TheUnholy, that's correct. The intent of this answer was to show how to use
find
to process files and not directories. The 'payload' of thefind
command (which is a simplesed
command in this case) can be modified to suit your needs. Aug 10, 2017 at 20:57
To springboard on paxdiablo's answer, I cobbled this alias together, and added it to my bash aliases as 'recursive sed': rsed
:
rsed() {
[[ -z $2 ]] && echo "usage: ${FUNCNAME[0]} oldtext newtext" && return
command find . -type f -exec sed -i "s/${1}/${2}/g" {} \;
}
Result:
> cat test/file
Hello how are you?
> rsed "Hello how are you?" "Fine thanks"
> cat test/file
Fine thanks