不要使用 sed
,使用 cut
:
grep .... | cut -c 1-N
如果您必须使用 sed
:
grep ... | sed -e 's/^\(.\{12\}\).*/\1/'
colrm x
例如,如果您需要前 100 个字符:
cat file |colrm 101
它已经存在多年并且在大多数 linux 和 bsd(肯定是 freebsd)中,通常是默认的。我不记得曾经输入过 apt-get install colrm
。
colrm
理解 utf8。
也不必使用 grep
一个例子:
sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file
严格使用 sed:
grep ... | sed -e 's/^\(.\{N\}\).*$/\1/'
要打印前 N 个字符,您可以删除直到行尾的 N+1 个字符:
$ sed 's/.//5g' <<< "defn-test"
defn
头呢?
echo alonglineoftext | head -c 9
cut
并没有削减它,而sed
可以。sed -r 's/^(.{12}).*/\1/'
。-r
显然在 Linux 上可用,但在 Mac 上不可用。cut -c 1-N
(其中 N 是一个数字)确实适用于我的 Cygwin 安装(cygwin v. 2.6,cut v. 8.25)在 OS X 上,使用sed -E
而不是sed -r
,在别处使用。