首页 > 解决方案 > 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.

标签: awksed

解决方案


实际上,我会为此使用edover 。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

推荐阅读