Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I indent a file such as its first line?

Example:

A file containing

     x=1+2+3+4+
5+6+7+8
+9+10+12

should be converted to

     x=1+2+3+4+
     5+6+7+8
     +9+10+12

I need this inside a shell-script on a Linux system. One-liners are preferred.

share|improve this question
    
does the first line always start with x=? –  amphibient Dec 13 '12 at 16:44
    
@foampile no, just an example –  jofel Dec 13 '12 at 16:48
    
are you limited to shell or can you use a scripting language? –  amphibient Dec 13 '12 at 16:53
    
@foampile I can use any common script language. Speed is less important. –  jofel Dec 13 '12 at 17:03
    
i was gonna suggest Perl. @Birei below posted a good answer. albeit i am increasingly liking awk as well –  amphibient Dec 13 '12 at 17:07

3 Answers 3

up vote 5 down vote accepted

One way using perl:

perl -pe 'if ($. == 1) { m/^(\s*)/; $space = $1 || q{}; next } s/^\s*/$space/' infile

It yields:

    x=1+2+3+4+
    5+6+7+8
    +9+10+12
share|improve this answer

With sed:

sed -e '1{h;s/[^[:blank:]].*//;x;b' -e '}' -e 'G;s/[[:blank:]]*\(.*\)\n\(.*\)/\2\1/'
share|improve this answer

You can do this in awk:

awk 'NR==1{split($0,a,/[^ \t]/)}{sub(/^[ \t]*/,a[1]);print}' file.in
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.