In this Letter we report the experimental demonstration of a new temporal shaping technique for x-ray free-electron lasers (FELs). This technique is based on the use of a spectrally shaped infrared (IR) laser and allows optical control of the x-ray generation process. By accurately manipulating the spectral amplitude and phase of the IR laser, we can selectively modify the electron bunch longitudinal emittance thus controlling the duration of the resulting x-ray pulse down to the femtosecond time scale. Unlike other methods currently in use, optical shaping is directly applicable to the next generation of high-average power x-ray FELs such as the Linac Coherent Light Source-II or the European X-FEL, and it enables pulse shaping of FELs at the highest repetition rates. Furthermore, this laser-shaping technique paves the way for flexible tailoring of complex multicolor FEL pulse patterns required for nonlinear multidimensional x-ray spectroscopy as well as novel multicolor diffraction imaging schemes.