Let's consider this test file:
$ cat file1
preceeding line
line I need to add spaces to
preceeding line
preceeding line
line I need to add spaces to
The following indents the non-indented lines to match the indent of the previous line:
$ awk '{if (/^[^ \t]/) $0=x $0; else {x=$0; sub(/[^ \t].*/, "", x);}} 1' file1
preceeding line
line I need to add spaces to
preceeding line
preceeding line
line I need to add spaces to
How it works
if (/^[^ \t]/) $0=x $0; else {x=$0; sub(/[^ \t].*/, "", x);}
If the line starts with neither a blank nor a tab, the add the indent x
to the start of the line.
Else, save the indentation from the current line in variable x
.
1
This is awk's cryptic shorthand for print-the-line.
Multi-line version
For those who prefer their code spread over multiple lines:
awk '
{
if (/^[^ \t]/)
$0=x $0
else {
x=$0
sub(/[^ \t].*/, "", x)
}
}
1' file1
Restricting the changes to lines 100 through 500
awk 'NR>=100 && NR<=500 {if (/^[^ \t]/) $0=x $0; else {x=$0; sub(/[^ \t].*/, "", x);}} 1' file1
Changing the file in-place
Using GNU awk:
awk -i inplace 'NR>=100 && NR<=500 {if (/^[^ \t]/) $0=x $0; else {x=$0; sub(/[^ \t].*/, "", x);}} 1' file1
Using BSD/OSX awk:
awk 'NR>=100 && NR<=500 {if (/^[^ \t]/) $0=x $0; else {x=$0; sub(/[^ \t].*/, "", x);}} 1' file1 >tmp && mv tmp file1
1Do you want all lines indented by 8 spaces? Or, do you want to match the indent on the preceding line? What if two or more non-indented lines appear in a row: should only the first be given an indent? Or, do they all get indents? – John1024 – 2016-08-29T19:27:30.553
Match the indent from the preceeding line. There should not be any non-indented lines that preceed the line I want to add, as long as we can match exactlly on the preceeding line. – user53029 – 2016-08-29T19:30:19.980
Let me clarify - there should not be any non-indented lines that would interfere, as long as we can match on the indented line to make the modification to the line below it. – user53029 – 2016-08-29T19:36:28.727
This looks like a simple case for Vim's auto indent. What happens when you start below the line with the correct indentation and call
– Shadoath – 2016-08-30T16:43:00.560==
? To do this to 100-500 start at line 101 (assuming 100 has the correct indent) and then type399==
to auto indent the next 399 line like the one above it.