Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert delimited file to fixed width in Linux

Tags:

linux

bash

Using tools available to bash, how do I convert delimited data

foo|bbbaaarrr|bazz

to fixed width data

foo      bbbaaarrrbazz     EOL   

I tried using column as the documentation implied I could define the column width, didn't work. I'm sure this is trivial using sed or awk, but I'm not familiar with them.

like image 543
Rick DeBay Avatar asked Dec 20 '22 07:12

Rick DeBay


1 Answers

The following should work for you:

column -t -s '|' input_file_here

It will convert the input file to table format. The input record separator is specified by -s. If you want something other than space padding in the fields, use -o to set the output separator. The output separator defaults to two spaces, so there will be two spaces between each column in the output.

Example:

$ cat input
hello|world|testing
a|b|c
another|test|line

$ column -t -s '|' input
hello    world  testing
a        b      c
another  test   line

http://man7.org/linux/man-pages/man1/column.1.html


Edit:

If you need each field to be a fixed length, you can use awk for that. You'll need to set the input delimiter for your file, but something like this should work:

$ awk -F '|' '{ for (i=1; i<=NF; i++) { printf("%-10s", $i); } print ""; }' input
hello     world     testing
a         b         c
another   test      line

Just change the field width specified in the printf statement.

like image 197
Mr. Llama Avatar answered Jan 03 '23 19:01

Mr. Llama