This post is a lose collection of useful applications of sed.
Grepping
The following commands are equivalent:
grep -r "et cetera" find . -type f -print | xargs sed -n '/et cetera/p'
The -n flag makes sed print only the matching lines.
Replacing Pathnames
The following command replaces the placeholder CURRENT_WORKING_DIR with the current working directory inside file.txt:
sed -i 's|CURRENT_WORKING_DIR|'$(pwd)'|g' file.txt
Replacing in a whole Directory Tree
We can use find to filter all files in a directory (tree) and then hand these files to sed. The following command prints out all true files (not directories) and lets sed replace the term et cetera with etc.
find . -type f -print | xargs sed -i 's/et cetera/etc./g'
While we could also use the -exec flag of find this separation of concerns makes it easy to dry-run the modifications by exchanging the sed command. The flag -n reduces the output to the matches only and the command p triggers the printing of matching lines.
find . -type f -print | xargs sed -n '/et cetera/p'
Tutorials
- [1] Colorful tutorial by grymoire