Skip to content
Advertisement

Sed/awk: Aligning words in a file

I have a file with the following structure:

# #################################################################
#   TEXT: MORE TEXT
#   TEXT: MORE TEXT
# #################################################################

___________________________________________________________________
ITEM 1
___________________________________________________________________
PROPERTY1:     VALUE1_1
PROPERTY222:   VALUE2_1
PROPERTY33:    VALUE3_1
PROPERTY4444:  VALUE4_1
PROPERTY55:    VALUE5_1

Description1:  Some text goes here
Description2:  Some text goes here

___________________________________________________________________
ITEM 2
___________________________________________________________________
PROPERTY1:     VALUE1_2
PROPERTY222:   VALUE2_2
PROPERTY33:    VALUE3_2
PROPERTY4444:  VALUE4_2
PROPERTY55:    VALUE5_2

Description1:  Some text goes here
Description2:  Some text goes here

I want to add another item to the file, using sed or awk:

 sed -i -r "$a$PROPERTY1:     VALUE1_3" file.txt
 sed -i -r "$a$PROPERTY2222:     VALUE2_3" file.txt

etc. So my next item looks like this:

___________________________________________________________________
ITEM 3
___________________________________________________________________
PROPERTY1:     VALUE1_3
PROPERTY222:     VALUE2_3
PROPERTY33:     VALUE3_3
PROPERTY4444:     VALUE4_3
PROPERTY55:     VALUE5_3

Description1:  Some text goes here
Description2:  Some text goes here

The column values is jagged. How do I align my values to the left like for previous items? I can see 2 solutions here:

  1. To align the values while inserting them into the file.
  2. To insert the values into the file the way I did it and align them next.

The command

sed -i -r "s|.*:.*|&|g" file.txt

catches the properties and values I want to align, but I haven’t been able to align them properly, i.e.

awk '/^.*:.*$/{ printf "%-40s %-70sn", $1, $2 }' file.txt

It prints out the file, but it includes the description values and tags, cuts the values if they include spaces or dashes. It just a big mess.

I’ve tried more commands based on what I’ve found on Stack Overflow and some blogs, but nothing does what I need.

Note: Values of the description tags are not jagged- this is because I write them to the file in a separate way.

What is wrong with my commands? How do I achieve what I need?

Advertisement

Answer

When your file is without tabs, try this:

sed -r 's/: +/:t/' file.txt | expand -20 

When this works, redirect the output to a tmpfile and move the tmpfile to file.txt.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement