Different methods to change the delimiter of a file
In this article, we will see different methods to change the delimiter of a file content, for example: from a comma to a colon.
Let’s use the following file as example:
1. Use awk
awk ‘$1=$1′ FS=”,” OFS=”:” file
In this command, FS and OFS are the special variables of awk, which means Input Field separator and Output field separator respectively. FS is assigned to the comma which is the input field separator, OFS is the output field separator which is the colon. $1=$1 actually does nothing here. It exists because there just should be some change in the data for awk to change the delimiter
2. Use sed
Here is the command with sed to do the task:
sed ‘s/,/:/g’ file
The character ‘s’in this command stands for substitution. What follows ‘s’ is the character, word or regular expression to be replaced with the next character. And the character ‘g’ here means that all commas in the files will be replaces with colons
3. Use awk with the gsub function
gsub means global substitution. It is somehow similar to the sub function. The difference is that, when sub only replaces the first occurrence, gsub will replace all the occurrences:
awk ‘gsub(“,”,”:”)’ file
4. Use tr
tr can be used for many things, ie to delete, to squeeze or to replace certain characters. In the following command, it is used to replace the commas with the colons:
5. Use perl
The command with perl is somehow similar to that with sed:
6. A more complicated method with perl
perl -F, -ane ‘print join “:”,@F;’ file
In this command, the elements of the line are autosplit (with the option -a) and stored into the default array(@F). We then join the array elements using colons and get them printed.
Comments are closed.