删除文件中行的开头

时间:2013-11-05 10:51:46

标签: linux bash sed

我有一个具有以下格式的文件:

21:26:54.21 PT  disconnected
21:26:56.18 CC1 received TCMTM
21:26:56.18 CC2 received TCMTM
21:26:56.18 TFT received TCMTM
21:26:56.18 FEC received TCMTM

我想删除每一行的第一部分(21:26:54.21),我试过这个:

sed "s/^[:digit:]*[:space:]//"  file.log

但它不起作用,我得到的输出与输入相同。

4 个答案:

答案 0 :(得分:5)

使用cut

$ cut -d' ' -f2- file
PT  disconnected
CC1 received TCMTM
CC2 received TCMTM
TFT received TCMTM
FEC received TCMTM

将空格设置为分隔符,并从字段2打印到最后一个(f2-)。

使用awk

$ awk '{$1=""}1' file  ## leading space :(
 PT disconnected
 CC1 received TCMTM
 CC2 received TCMTM
 TFT received TCMTM
 FEC received TCMTM

将第一个字段设置为空。

$ awk '{for (i=1;i<=NF; i++) $i=$(i+1); NF=NF-1}1' file
PT disconnected
CC1 received TCMTM
CC2 received TCMTM
TFT received TCMTM
FEC received TCMTM

它将字段数减1,将每个字段移到前一个(因此,第一个被删除)。

使用sed

$ sed 's/^[^ ]* //g' file
PT  disconnected
CC1 received TCMTM
CC2 received TCMTM
TFT received TCMTM
FEC received TCMTM

删除从行首到第一个空格的所有内容。

或基于您的sed

$ sed "s/^[0-9:.]* //g" file
PT  disconnected
CC1 received TCMTM
CC2 received TCMTM
TFT received TCMTM
FEC received TCMTM

从第一行开头删除所有字符0-9:.

答案 1 :(得分:2)

使用awk

awk '{$1=x;sub(/^ /,x)}1' file
PT disconnected
CC1 received TCMTM
CC2 received TCMTM
TFT received TCMTM
FEC received TCMTM

另一个版本

awk '{sub(/^[0-9:.]+ /,x)}1' file

另一个

awk '{sub(/[^ ]* /,x)}1' file

答案 2 :(得分:0)

使用sed:

sed 's/^[0-9:.]* *//' file.log

输出:

PT  disconnected
CC1 received TCMTM
CC2 received TCMTM
TFT received TCMTM
FEC received TCMTM

答案 3 :(得分:0)

除了缺少时间戳中需要匹配的:.之外,您在使用字符类方面有轻微错误:

sed "s/^[[:digit:]:.]*[[:space:]]//" file.log

[:digit:]等字符类仅在[...]内有效,因此您需要

s/^[[:digit:]]*

匹配行首的零个或多个数字。您仍然需要匹配:.,因此也要将它们添加到[...]

s/^[[:digit:].:]*

[:digit:]视为0-9的替代,而不是[0-9]。你可以用

写上面的内容
s/^[0-9.:]*

将匹配数字0,1,2,3,4,5,6,7,8,9,但不包括当前区域设置中可能被视为数字的任何其他字符。