首页 > 解决方案 > 仅打印每行的第一个和第二个单词以使用 sed 输出

问题描述

我想清理一个模式文件供以后使用,所以只有第一个和第二个单词(或数字)是相关的。

我有这个:

模式.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

输出.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 指出的那样,包括以下情况是有意义的:带有空格的字符串,引号前后带有空格的字符串,字符串中的注释和引号之后的注释。接受的答案 sed 解决方案适用于所有这些。

标签: awksed

解决方案


仅完全基于您显示的示例,这可以很容易地完成awk。使用 GNU 编写和测试awk,应该适用于任何awk.

awk '{sub(/\r$/,"")} NF && !/^#/{print $1,$2}'  Input_file

说明:这里只需检查 2 个条件。1st-NF确保行不是空行。第二行不是以 # 开头,然后打印当前行的第一列和第二列。



sed请在 GNU 中尝试以下操作sed

sed -E 's/\r$//;/^#/d;/^\s*$/d;s/^ +//;s/([^ ]*) +([^ ]*).*/\1 \2/' Input_file

或根据 Ed sir 的评论使用以下内容:

sed -E 's/\r$//; /^#/d; /^\s*$/d; s/^\s+//; s/(\S*)\s+(\S*).*/\1 \2/' Input_file

上述两种解决方案的示例输出如下:

some_variable one
some_other_var 2
different_var "hello"
var_after_newlines 18

推荐阅读