135

使用sed什么是单行来打印前n 个字符?我正在执行以下操作:

grep -G 'defn -test.*' OctaneFullTest.clj  | sed ....
4

6 回答 6

250

不要使用sed,使用cut

grep .... | cut -c 1-N

如果您必须使用sed

grep ... | sed -e 's/^\(.\{12\}\).*/\1/'
于 2009-02-11T20:42:17.690 回答
55
colrm x

例如,如果您需要前 100 个字符:

cat file |colrm 101 

它已经存在多年并且在大多数 linux 和 bsd(肯定是 freebsd)中,通常是默认的。我不记得曾经需要打字apt-get install colrm

于 2011-06-02T10:22:58.630 回答
10

也不必使用 grep

一个例子:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file
于 2009-12-14T07:46:58.433 回答
7

严格使用 sed:

grep ... | sed -e 's/^\(.\{N\}\).*$/\1/'
于 2009-02-11T20:48:40.030 回答
7

要打印前 N 个字符,您可以删除直到行尾的 N+1 个字符:

$ sed 's/.//5g' <<< "defn-test"
defn
于 2016-12-20T22:43:40.730 回答
5

呢?

echo alonglineoftext | head -c 9
于 2020-01-08T21:51:49.957 回答