How to convert space delimited to tab delimited. How to use tab in unix shell script. How to replace delimitter in Unix using shell script. replace multiple spaces with tab. convert spaces to tabs. Convert space delimited to tab delimited. use tab in unix shell script in a function for different columns.

How to use tab in Unix Shell Script (convert space to tabs) with examples

In this article I will share the steps to display equal alignment of multiple columns i.e. to convert space delimited to tab delimited using shell script.

 

Example to use TAB in Unix Shell Script

Below is a sample one liner example to print multiple columns with a tab using printf. here you can give a tab length as per your requirement.

[root@master ~]# printf "%-20s%-20s%-20s\n" "col1" "col2" "col3"
col1                col2                col3

 

 
To use tab in Unix shell script in a function you can use below solution

[root@master ~]# cat /tmp/align_column_with_tabs.sh
#!/bin/bash

function align_output {

   str_length=`echo -n $1 | wc -c`
   tab_length=`expr 15 - $str_length - 6`
   echo -n -e "$1"
   printf "%${tab_length}s"
   printf ": $2\n"
}

align_output col1 col2
align_output col3 col4
align_output col5 col6

 

Here you can modify the highlighted value to change the tab length between columns. Now when we run the script, the output would look like below

[root@master ~]# /tmp/align_column_with_tabs.sh
col1     : col2
col3     : col4
col5     : col6

 

Lastly I hope the steps from the article to convert space delimited to tab delimited and use tab in Unix shell script was helpful. So, let me know your suggestions and feedback using the comment section.

 

Leave a Reply

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