engo473
engo473

Reputation: 15

Aligning comments in a bash file

How would I go about rearranging the comments in a file so that all the comments are aligned on the rights 2 spaces after the longest line?

Upvotes: 1

Views: 204

Answers (1)

Slawomir Dziuba
Slawomir Dziuba

Reputation: 1325

You can do it in sed using a trick. The main problem is counting the number of escape characters in sed taking into account bash dodges. We temporarily replace # with a unique character (I used ___) for lines that are not a comment, and finally undo the replacement.

I use a substitute IF for sed in form /pattern/{s/source/destination/}

sed -e $'/^#.*$/{s/#/___/g};/echo \" /{s/#/___/};/echo \\\\\\\\" /{s/#/___/};s/ #/\001#/;s/^$/\001/;s/___/#/g' zzz.txt | column -ts $'\001'

EDIT:

I made a small correction so that 2 # in 1 line would not be moved. Now the result is exactly like the example.

input data:

# begins with #
  # begins with space    
A=1
B=(bax qux)  # comment
  C=(2 3)  # don't change indentation
echo ${#A[@]}  # first # doesn't begin a word
echo "  # not a comment"
echo \"  # comment\"
echo \\"  # not a comment\\"

output data:

# begins with #
                              # begins with space
A=1
B=(bax qux)                   # comment
  C=(2 3)                     # don't change indentation
echo ${#A[@]}                 # first # doesn't begin a word
echo "  # not a comment"
echo \"                       # comment\"
echo \\"  # not a comment\\"

This is a single-line script and for simple applications such as the example is sufficient. If there were a lot more additional rules, I would be inclined to set macros in m4 or similar solutions.

Upvotes: 1

Related Questions