【发布时间】:2019-05-09 05:22:02
【问题描述】:
假设您想使用以下两种方法之一从数据文件中删除 cmets:
cat file.dat | sed -e "s/\#.*//"
cat file.dat | grep -v "#"
这些单独的方法是如何工作的,它们之间有什么区别?一个人是否也可以将干净的数据写入新文件,同时避免任何可能的警告或错误消息最终出现在该数据文件中?如果是这样,你会怎么做呢?
【问题讨论】:
假设您想使用以下两种方法之一从数据文件中删除 cmets:
cat file.dat | sed -e "s/\#.*//"
cat file.dat | grep -v "#"
这些单独的方法是如何工作的,它们之间有什么区别?一个人是否也可以将干净的数据写入新文件,同时避免任何可能的警告或错误消息最终出现在该数据文件中?如果是这样,你会怎么做呢?
【问题讨论】:
grep -v 将丢失所有带有# 的行,例如:
$ cat file
first
# second
thi # rd
所以
$ grep -v "#" file
first
将删除所有带有# 的行,这是不利的。相反,您应该:
$ grep -o "^[^#]*" file
first
thi
就像sed 命令一样,但这样你就不会得到空行。 man grep:
-o, --only-matching
Print only the matched (non-empty) parts of a matching line,
with each such part on a separate output line.
【讨论】:
这些单独的方法是如何工作的,有什么区别 他们之间?
是的,尽管 sed 和 grep 是 2 个不同的命令,但它们的工作方式相同。您的sed 命令只是将所有具有# 的行替换为NULL。另一方面,grep 将简单地跳过或忽略那些将跳过其中包含 # 的行的行。
您可以通过手册页获得更多信息,如下所示:
man grep:
-v, --invert-match Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.)
man sed:
s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The更换可能 包含特殊字符 & 以引用匹配的模式空间部分,特殊转义 \1 通过 \9 到 参考正则表达式中对应的匹配子表达式。
一个人是否也可以将干净的数据写入 新文件,同时避免任何可能的警告或错误消息 最终在那个数据文件中?
是的,我们可以通过在两个命令中使用 2>/dev/null 来重定向错误。
如果是这样,你会怎么做?
你可以试试2>/dev/null 1>output_file
sed 命令的解释: 现在也添加sed 命令的解释。这仅用于理解目的,无需使用cat,然后使用sed,您可以使用sed -e "s/\#.*//" Input_file。
sed -e " ##Initiating sed command here with adding the script to the commands to be executed
s/ ##using s for substitution of regexp following it.
\#.* ##telling sed to match a line if it has # till everything here.
//" ##If match found for above regexp then substitute it with NULL.
【讨论】: