Change indentation in scripts

Hi,

I am a professional in writing shell scripts,
and I am using a one-space indentation like this

for i in file1 file2
do
 if [ -f "$i" ]
 then
  echo "$i"
 fi
done

so very deeply nested stuff still fits on my screen.
At release time I usually double the indentation via

sed 's/^ */&&/'

to make it better readable for others.

Now my question: how to do the reverse?
I.e. if I get a released script back for a rework, how can I get half of the indentation?

Just a suggestion, how about using awk ?

awk ' {
        match($0, /^[ \t]*/)
        if ( (RSTART + RLENGTH ) > 1 )
                print substr($0, RSTART, RLENGTH / 2) substr($0, RSTART + RLENGTH)
        else
                print $0
} ' file
1 Like

Thanks for bringing the match() function to my attention.
Indeed this is the solution!

Yikes, if stuff is that deeply nested the programming gods are telling you it's time for some functions and/or simplification.

I worked for a software house where one of their programming rules was all functions must exit at the bottom (no returning in the middle) and a lot of their code ended up with huge nested levels, as each validation you did pushed everything else over 1 more indent.

Yes, much better not to nest that much. I agree with chubler_xl advice.

chubler_XL is correct. I use 5 spaces indentation and if a line doesn't fit within 80 characters i think hard if it is really good to do it that way (in most cases it isn't and it is the rare exception if it is).

To reduce the indentation in sed (replace "<b>" and "<t>" with literal blanks/tabs):

sed ':search
     /^<b><b>/ {
                 s/^\([<b>]*\)\(<b><b>\)\([^<b>]\)/\1;\3/
                 b search
              }

     :replace
     /^;/     {
                 s/^\(;*\);/\1<b>/
                 b replace
              }' /path/to/input

You can easily adapt this to other levels of indentation by modifying the parts marked bold to contain more or less blanks. Note that lines have to start leftmost - no effort is made to deal with lines not starting at character position 1.

I hope this helps.

bakunin

I agree that long lines should be avoided, but there is a trivial way to cut the number of leading spaces on every line in a file in half:

sed 's/^\( *\)\1/\1/'
2 Likes

Nice one Don

Brilliant!!