0

I want to print lines which start from second column (first column is white space).

$ cat test.txt

first
 second
  third
   four
 second
    five
      seven

Output should be:

 second


 second

When the line starts from the 7th column then the output should be:

      seven

2 Answers 2

2

You can use ^\s\S regex:

$ cat test.txt
first
 second
  third
   four
 second
    five
      seven
$ grep "^\s\S" test.txt
 second
 second
  • ^ stands for "line starts with",
  • \s means "first character is a white space",
  • \S for "following character is not a whitespace.

This way, you get every line beginning with a single whitespace.

If you want lines beginning with n whitespaces, add {n}:

$ grep "^\s\{1\}\S" test.txt
 second
 secon d
$ grep "^\s\{2\}\S" test.txt
  third
$ grep "^\s\{3\}\S" test.txt
   four
$ grep "^\s\{4\}\S" test.txt
    five
$ grep "^\s\{5\}\S" test.txt
$ grep "^\s\{6\}\S" test.txt
      seven
0

Really simple solution for the second version:

 echo "first
 second
  third
   four
 second
    five
      seven" | grep -e '^ ' | grep -ve '^  '

[Edit] - now working with only the withespaces at the begining of the line

2
  • 1
    What if a line contains multiple spaces (for example, second is replaced with second line)?
    – ssssteffff
    Apr 23, 2014 at 8:55
  • Correct, added that - Anyway, you solution is much cleaner @ssssteffff
    – Blitz
    Apr 23, 2014 at 9:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .