The requirements as written are ambiguous.
Code:
This matches
This matches
# this matches
#$ this matches
Line 3 has spaces which can be considered "content", so it gets a tab added too.
The last line is empty, but exists. No tab is added.
Must the 1st column always have a non-space character or not?
If it was me and I didn't have perl, I'd use a 2-stage solution.
- add the tab the the beginning of every line -e s/^/\t/g
- remove the tab on all lines that don't have any other content -e s/\t$//g
That would look like:
Code:
$ sed -e 's/^/\t/g' -e 's/^\t$//g' {input_file}
I tested the above input file with that and it appeared to work to me.
With perl, we can do smarter matching and grouping so the prior match isn't just removed, but captured for use later. Very handy when we need to swap columns in code. Of course, swapping columns is trivial in vim.
If you want to include whitespace in the definition of content, but only at the front of the line. Then questions about the requirements still exist. In perl, a little function that removes all leading and trailing whitespace is handy:
Code:
$line =~ s/^\s+|\s+$//go;
I don't think sed supports \s. Maybe there is a -E options for full regex support in sed? Seems so from the sed manpage:
Code:
-E, -r, --regexp-extended
use extended regular expressions in the script (for portability use
POSIX -E).
Bookmarks