How to use the command 'iconv' (with examples)
The iconv
command is used to convert text from one encoding to another. It is especially useful when dealing with files that have different character encodings.
Use case 1: Convert file to a specific encoding, and print to stdout
Code:
iconv -f from_encoding -t to_encoding input_file
Motivation: This use case is helpful when you want to convert the encoding of a file and directly print it to the standard output without saving it to a separate file.
Explanation:
from_encoding
: Specifies the encoding of the input file.to_encoding
: Specifies the encoding to which the input file should be converted.input_file
: Specifies the file that needs to be converted.
Example Output: If we have a file named “example.txt” encoded in UTF-8 and we want to convert it to ASCII, we can use the following command:
iconv -f UTF-8 -t ASCII example.txt
This will convert the file “example.txt” from UTF-8 encoding to ASCII encoding and print the converted text to the standard output.
Use case 2: Convert file to the current locale’s encoding, and output to a file
Code:
iconv -f from_encoding input_file > output_file
Motivation: This use case is helpful when you want to convert the encoding of a file and save the converted text to a separate file.
Explanation:
from_encoding
: Specifies the encoding of the input file.input_file
: Specifies the file that needs to be converted.output_file
: Specifies the file to which the converted text should be saved.
Example Output: If we have a file named “example.txt” encoded in UTF-8 and we want to convert it to the encoding of the current locale (e.g., UTF-16), we can use the following command:
iconv -f UTF-8 example.txt > converted.txt
This command will convert the file “example.txt” from UTF-8 encoding to UTF-16 encoding and save the converted text to a file named “converted.txt”.
Use case 3: List supported encodings
Code:
iconv -l
Motivation: This use case is useful when you want to know the encodings supported by the iconv
command.
Explanation:
No additional arguments are required for this use case. Simply running the command iconv -l
will list all the supported encodings.
Example Output:
Running the command iconv -l
will provide a long list of supported encodings, such as “UTF-8”, “ISO-8859-1”, “UTF-16”, “ASCII”, etc.