The best tool for non-interactive in-place file editing is
ex -sc '%s/\(\.com\).*/\1/ | x' file.txt
If you've used
vi and if you've ever typed a command that begins with a colon
: you've used an ex command. Of course many of the more advanced or "fancy" commands you can execute this way are Vim extensions (e.g.
:bufdo) and are not defined in the POSIX specifications for
ex, but those specifications allow for a truly astonishing degree of power and flexibility in non-visual text editing (whether interactive or automated).
The command above has several parts.
-s enables silent mode to prepare
ex for batch use. (Suppress output messages et. al.)
-c specifies the command to execute once the file (
file.txt, in this case) is opened in a buffer.
% is an address specifier equivalent to
1,$—it means that the following command is applied to all lines of the buffer.
s is the substitute command that you are likely familiar with already. It is commonly used in
vi and has essentially identical features to the
s command of
sed, though some of the advanced regex features may vary by implementation. In this case from ".com" to the end of the line is replaced with just ".com".
The vertical bar separates sequential commands to be executed. In many (most)
ex implementations you can also use an additional
-c option, like so:
ex -sc '%s/\(\.com\).*/\1/' -c x file.txt
However, this is not required by POSIX.
x command exits, after writing any changes to the file. Unlike
wq which means "write and quit",
x only writes to the file if the buffer has been edited. Thus if your file is unaltered, the timestamp will be preserved.