How to replace multiple spaces with comma in Bash – Linux Tips And Tricks



How to replace multiple spaces with comma in Bash – Linux Tips And Tricks

How to replace multiple spaces with comma in Bash - Linux Tips And Tricks

The Linux command tr translates, squeezes and/or delete characters from standard input, writing to standard output.

-s mean to squeeze

To replace multiple spaces with a single space in a Bash script, you can use the tr command. Here’s an example command that does this

echo “Once upon a time, there were only trees.” | tr -s ‘ ‘

This will output:
Once upon a time, there were only trees.

The tr command with the -s option squeezes repeated occurrences of the specified character, which in this case is a space, into a single instance.

You can also use this command to modify a file in place by redirecting the output to a new file and then moving it over the original file.

tr -s ‘ ‘ #file.txt# newfile.txt && mv newfile.txt file.txt

This will modify file.txt by replacing multiple spaces with a single space.

To replace multiple spaces with a comma in BASH, you can use the tr command. Here’s an example command that does this.
echo “Once upon a time, there were only trees.” | tr -s ‘ ‘ ‘,’

This will output.
Once,upon,a,time,there,were,only,trees.

To replace multiple spaces with a comma in BASH, you can also use the sed command. But note that it delimits onyl space and include comma but the tr command delimits all spaces and comma. Here’s an example command that does this.

echo “Once upon a time, there were only trees.” | sed ‘s/ */,/g’

This will output.
Once,upon,a,time,,there,were,only,trees.

#linux #ubuntu #redhat #bash