Skip to content
Home ยป How to Convert the Space(s) to a Comma in a Linux File?

How to Convert the Space(s) to a Comma in a Linux File?

I want to convert the space(s) in a Linux file to a comma.

 

Problem

How to convert the space(s) to a comma in a Linux file?

 

Solution

For example, you have a test.txt file as shown in the image below:

The test.txt file

 

Use the command below if you want to convert the space to a comma:

tr -s '[:blank:]' ',' < test.txt

 

So that your file will convert to the image below:

Convert a space to a comma

 

Not only that, the command can also be used if you have a file that has irregular spaces as shown in the image below:

Convert an irregular space to a comma

 

Even the above command can also convert the free space created using the Tab key, as shown in the image below:

convert the space(s) to a comma
Convert a Tab space to a comma

 

You can also use the below command in addition to the above command to make the space(s) in a Linux file a comma:

sed 's/\s\+/,/g' < test.txt
convert the space(s) to a comma
Convert the space(s) using the sed command

 

Note

If you want the free space to convert to something other than a comma, for example, to a colon (:), Then convert the comma in both commands above to become a colon as in the command below:

tr -s '[:blank:]' ':' < test.txt 
convert the space(s) to a comma
Convert the space(s) to a colon

 

References

unix.stackexchange.com
stackoverflow.com

image_pdfimage_print
Visited 50 times, 1 visit(s) today
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *