awk和上一行变量的问题

时间:2015-09-15 13:04:04

标签: bash awk sh gawk

代码通常比千字节更好。这个演示代码也不遵守我的逻辑。通常我相信编译器和程序,所以我认为我有一个错字或某种东西。 拜托,你能指出我吗?

copy&将下面的代码粘贴到mydemo.sh文件中,然后使用命令sh ./mydemo.sh

运行它

在我的参考系统中打印出来:

mytux:~# ./mydemo.sh
This should spit out:
{USER1NAME} {Firstname Surname} {user1name}
{USER2NAME} {Secondname Surname} {user2name}
{USER3NAME} {Thirdname Surname} {user3name}
---- but it spits out:
{USER1NAME} {somestring: user1name}, {user1name}
{USER2NAME} {somestring: user2name}, {user2name}
{USER3NAME} {somestring: user3name}, {user3name}
----
Why so and how to fix it?

以及代码:

#!/bin/sh
echo "# Firstname Surname, Company">usernames.txt
echo "somestring: user1name">>usernames.txt
echo "# Secondname Surname, Company">>usernames.txt
echo "somestring: user2name">>usernames.txt
echo "# Thirdname Surname, Company">>usernames.txt
echo "somestring: user3name">>usernames.txt

echo "This should spit out:"
echo "{USER1NAME} {Firstname Surname}, {user1name}"
echo "{USER2NAME} {Secondname Surname}, {user2name}"
echo "{USER3NAME} {Thirdname Surname}, {user3name}"
echo "---- but it spits out:"
echo "{USER1NAME} {somestring: user1name}, {user1name}"
echo "{USER2NAME} {somestring: user2name}, {user2name}"
echo "{USER3NAME} {somestring: user3name}, {user3name}"
echo "---- See:"
cat usernames.txt|awk \
        'BEGIN { $mylink="";} \
        { \
                if(match($0,"^#")!=0) \
                { \
                        split($0, a, ","); \
                        $mylink=$a[1]; \
                } \
                else \
                { \
                        if(length($mylink)>0) \
                        { \
                                print "{" toupper($2) "} {" $mylink "}, {" $2 "}"; \
                        } \
                        $mylink=""; \
                } \
        }'
echo "----"
echo "Why so and how to fix it?"

1 个答案:

答案 0 :(得分:1)

这是你想要实现的目标吗?按原样发布输入文本会更容易。

$ awk -F"[, ]" -v OFS="}, {" '
        /^#/{n=$2" "$3;next} 
            {print "{" toupper($2), n, $2"}"}
         ' usernames.txt

{USER1NAME}, {Firstname Surname}, {user1name}
{USER2NAME}, {Secondname Surname}, {user2name}
{USER3NAME}, {Thirdname Surname}, {user3name}