I find myself using basically the same line over and over again:
cat file | command1 | command2 | command3 > file
Is there a way I can put all these pipes into one script, so I can just run
and accomplish the same thing?
Create a file with this content:
Make it executable:
And call it as:
then call it like:
to use a real example:
And just to be pedantic, it's slightly better form to write the output to a temporary file, then at the end move the tempfile over the original file.
You can make a script or function that contains this command. Use
There's a major bug in your code snippet: depending on the timing,
The recommended way to modify a file is to write to a new temporary file, and once this is finished, move it to replace the old version. This way, if something bad happens to interrupt the processing (such as an error, a power failure, etc.), the old file remains in place.
Here is a function that operates on this principle. Thanks to the
Put this function in your
You can make the function act on all of its arguments in turn by putting that stuff in a loop.
If you want to make a script instead, put the code in a file starting with a shebang line to indicate that it's a shell script.
Put the file in your command search path and make it executable (see How can I make a program executable from everywhere).
Another way to solve the truncate-before-use problem is the sponge utility, but this utility isn't available everywhere (it's from Debian).