【发布时间】:2021-03-15 15:27:40
【问题描述】:
我想清理一个模式文件供以后使用,所以只有第一个和第二个单词(或数字)是相关的。
我有这个:
pattern.txt
# This is a test pattern
some_variable one # placeholder which replaces a variable
some_other_var 2 # other variable to replace
# Some random comment in between
different_var "hello" # this will also replace a placeholder but with a string
# And after some empty lines:
var_after_newlines 18 # some variable after a lot of newlines
{{hello}} " this is just a string surrounded by space "
{bello} "this is just a string"#and this is a comment
cello "#string with a comment in it"#and a comment
我申请的对象:
sed -nE '/^\s*#/d;/^\s*$/d;s/^\s*([^\s]+)\s+([^\s]+).*$/\1 \2/p' pattern.txt > output.txt
- 它应该清除以 # 开头的注释行 -> 有效
- 它应该清除空行(或带有空白字符的行)-> 有效
- 它应该用由一 (1) 个空格字符分隔的第一个和第二个单词替换每一行 -> 不起作用。比较:
output.txt
期望:
some_variable one
some_other_var 2
different_var "hello"
var_after_newlines 18
{{hello}} " this is just a string surrounded by space "
{bello} "this is just a string"
cello "#string with a comment in it"
现实:
different_var "hello" # thi
var_after_newline
{{hello}} " thi
{bello} "thi
cello "#
我错过了什么?
编辑:
正如@Ed Morton 指出的那样,包括以下情况是有意义的:带空格的字符串、引号前后带空格的字符串、字符串中的 cmets 和引号之后的 cmets。接受的答案 sed 解决方案适用于所有这些。
【问题讨论】:
-
如果一行只有1个“单词”应该打印什么?如果该行只是
var # 1 word and a comment,应该打印什么?如果线路是var " string surrounded with space "怎么办?如果是var "#string surrounded by#"怎么办?请edit你的例子包括这些案例。