Truncating Data in Bash

  • Read
  • Discuss

​​In this tutorial, we will learn how to truncate or shorten data stored in a file in Bash. There are several ways to achieve this, and we will cover three of them in this tutorial: Using the > operator, the truncate command, and the : > operator.

Truncating Data Using the > Operator

The > operator can overwrite a file’s contents with new data, effectively truncating its previous contents. For example, the following command will truncate the contents of a file named “data.txt”:

echo "" > data.txt

The following will be the output.

The above command writes an empty string to “data.txt” and overwrites its previous contents.

Truncating Data Using the truncate Command

The truncate command is used to resize a file to a specified size. For example, the following command will truncate the contents of “file.txt” to zero bytes:

truncate -s 0 file.txt

The -s option is used to specify the size to which the file should be truncated. In this case, the size is 0 bytes.

Truncating Data Using the : > Operator

The : > operator is similar to the > operator and is used to truncate the contents of a file to zero bytes. For example, the following command will truncate the contents of “file.txt”:

: > file.txt

The following will be the output.

This operator writes the : character to the file, effectively truncating its previous contents.

Leave a Reply

Scroll to Top