awk - How can I use sed to generate an awk file?
问题描述
How do I write sed commands to generate an awk file.
Here is my problem: For example, I have a text file, A.txt which contains a word on each line.
app#
#ple
#ol#
The # refers when the word starts/ ends/ starts and ends. For example, app# shows that the word starts with 'app'. #ple shows that the word ends with 'ple'. #ol# shows that the word has 'ol' in the middle of the word.
I have to generate an awk file from sed commands which reads in another file, B.txt (which contains a word on each line) and increments the variable start, end, middle.
How do I write sed commands whereby for each line in the text file, A.txt, it will generate an awk code ie.
{ {if ($1 ~/^app/)
{start++;}
}
For example, if I input the other file, B.txt with these words into the awk script,
application
people
bold
cold
The output would be; start = 1, end = 1, middle = 2.
解决方案
实际上,我会为此使用ed
over 。sed
A.awk
一个从以下位置创建A.txt
并运行它的快速脚本B.txt
:
#!/bin/sh
ed -s A.txt <<'EOF'
1,$ s!^#\(.*\)#$!$0 ~ /.+\1.+/ { middle++ }!
1,$ s!^#\(.*\)!$0 ~ /\1$/ { end++ }!
1,$ s!^\(.*\)#!$0 ~ /^\1/ { start++ }!
0 a
#!/usr/bin/awk -f
BEGIN { start = end = middle = 0 }
.
$ a
END { printf "start = %d, end = %d, middle = %d\n", start, end, middle }
.
w A.awk
EOF
# awk -f A.awk B.txt would work too, but this demonstrates a self-contained awk script
chmod +x A.awk
./A.awk B.txt
运行它:
$ ./translate.sh
start = 1, end = 1, middle = 2
$ cat A.awk
#!/usr/bin/awk -f
BEGIN { start = end = middle = 0 }
$0 ~ /^app/ { start++ }
$0 ~ /ple$/ { end++ }
$0 ~ /.+ol.+/ { middle++ }
END { printf "start = %d, end = %d, middle = %d\n", start, end, middle }
注意:这假定中间模式不应该在一行的开头或结尾匹配。
但是这里尝试使用 sed 创建 A.awk,将所有 sed 命令放在一个文件中,因为尝试将其作为单线使用-e
并正确进行所有转义并不是我目前想做的事情:
内容makeA.sed
:
s!^#\(.*\)#$!$0 ~ /.+\1.+/ { middle++ }!
s!^#\(.*\)!$0 ~ /\1$/ { end++ }!
s!^\(.*\)#!$0 ~ /^\1/ { start++ }!
1 i\
#!/usr/bin/awk -f\
BEGIN { start = end = middle = 0 }
$ a\
END { printf "start = %d, end = %d, middle = %d\\n", start, end, middle }
运行它:
$ sed -f makeA.sed A.txt > A.awk
$ awk -f A.awk B.txt
start = 1, end = 1, middle = 2
推荐阅读
- c# - 在 OWIN 自托管中使用集成的 Windows 身份验证发送大型 POST 请求
- javascript - 如何在 React useRef 中设置 refs
- ios - 使用 Firebase 登录 Twitter iOS 的 OAuthProvider 有错误的构造函数
- python - 如何在 Spyder 4 中禁用关键字/文本建议?
- sql - SQL - 将表中的行组显示为列
- javascript - 如何使用 vue 渲染函数将使用 JavaScript 创建的 Dom 节点添加到 vue
- sql - 如何将中值注释到 django 查询集
- android - 如何在 Android 设备上解决 Qt 应用程序的 ClassNotFoundEception?
- c++ - 实现 Z 缓冲区算法
- python-3.x - 在python中合并数据框