我想打印从第二列开始的行(第一列是空格)。
$ cat test.txt
first
second
third
four
second
five
seven
输出应该是:
second
second
当该行从第 7 列开始时,输出应该是:
seven
答案1
您可以使用^\s\S
正则表达式:
$ cat test.txt
first
second
third
four
second
five
seven
$ grep "^\s\S" test.txt
second
second
^
代表“行开头为”,\s
表示“第一个字符是空格”,\S
对于“后面的字符不是空格。
这样,每一行都以一个空格开头。
如果您希望行以空格开头n
,请添加{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
答案2
第二个版本的解决方案非常简单:
echo "first
second
third
four
second
five
seven" | grep -e '^ ' | grep -ve '^ '
[编辑]-现在只处理行首的空格