使用sed搜索降价
问题
我在一个文件夹中放置了多个 Markdown 文件,格式如下...
# Cool Project
* Random Text
* Other information
TODO: This is a task
TODO: This is another task
# Cool Project
* Random Text
* Other information
TODO: This is a task
TODO: This is another task
我编写了一个脚本,可以从所有文件中提取以 TODO 开头的所有字符串......
这给了我这样的输出
TODO: This is a task
TODO: This is another task
我想知道是否有可能使用 sed 从模式中向后看来识别和拾取以开头的行/^# /并将其附加到字符串的末尾......像这样
TODO: This is a task # Cool Project
TODO: This is another task # Cool Project
回答
你可以在一个人中做到这一点awk。使用您显示的示例,您能否尝试使用 GNU 进行以下、编写和测试awk。
awk '/^# /{val=$0;next} /^TODO/{print $0,val}' Input_file
说明:为以上添加详细说明。
awk ' ##Starting awk program from here.
/^# /{ ##Checking condition if line starts from hash space then do following.
val=$0 ##Creating val which has current line value getting stored init here.
next ##next will skip all statements from here.
}
/^TODO/{ ##Checking condition if line starts with TODO then do following.
print $0,val ##Printing current line and val here.
}
' Input_file ##Mentioning Input_file name here.
回答
使用 sed:
sed -n '/^#/h;/^TODO/{G;s/n/ /p}' file
搜索以 # 开头的行并添加到保留空间 (h) 然后当一行以“TODO”开头时,将保留空间附加到模式空间 (G) 并用新行替换一个空格。