awk
is also useful for such things. If you set the output field separator OFS
:
$ awk -F"." -v OFS="_" '{print $1, $2}' file
6_5
6_10
7_2
10_11
But if you really need sed
use back references (here with extended regular expressions — note that the option is sometimes -E
and sometimes only basic regular expressions are supported by sed
):
$ sed -r 's/([0-9]+)\.([0-9]+).*/\1_\2/' file
6_5
6_10
7_2
10_11
If you want to perform in-place replacing, you can either say awk/sed '...' file > tmp_file && mv tmp_file file
or, use sed -i
(on those platforms where it is supported, but note that there are differences between GNU sed
and BSD (macOS) sed
), or gawk -i inplace
(GNU Awk).
Note in both cases I am using a single command instead of piping to another one.