awk - 仅打印每行的第一个和第二个单词以使用 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
- 它应该清除以 # -> works 开头的注释行
- 它应该清除空行(或带有空格字符的行)-> 有效
- 它应该用由一 (1) 个空格字符分隔的第一个和第二个单词替换每一行 -> 不起作用。相比:
输出.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 解决方案适用于所有这些。
解决方案
仅完全基于您显示的示例,这可以很容易地完成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
推荐阅读
- node.js - 我如何让一个不和谐的机器人 DM 成为它刚刚踢的人?
- libreoffice-base - 发生异常类型:com.sun.star.lang.IllegalArgumentException 消息:不支持的 URL <>:“来自 LoadEnv::startLoading”
- reactjs - React - 如果它只是一个向下传递的回调,那么命名一个 onClick 函数 ...Handler 是一种好习惯吗?
- python - 无法安装 Geopandas
- python - 连接到远程代理和消费者结果,没有消息
- python-3.x - 如何将列表拆分为数字平方长度的列表列表?
- php - 使用 SQL 修改 wordpress 用户的角色
- javascript - 嗨,只是想在 iframe 中编辑 CSS
- javascript - JS:事件分配
- javascript - 在 Javascript 中的 iFrame 中触发滚动事件的问题