Processing of awk with multiple variable from previous processing?

旧巷老猫 提交于 2020-01-17 01:23:07

问题


I have a Q's for awk processing, i got a file below

cat test.txt

/home/shhh/
abc.c
/home/shhh/2/
def.c
gthjrjrdj.c
/kernel/sssh
sarawtera.c
wrawrt.h
wearwaerw.h

My goal is to make a full path from splitting sentences into /home/jhyoon/abc.c.

This is the command I got from someone:

cat test.txt | awk '/^\/.*/{path=$0}/^[a-zA-Z]/{printf("%s/%s\n",path,$0);}'

It works, but I do not understand well about how do make interpret it step by step.

Could you teach me how do I make interpret it?

Result :

/home/shhh//abc.c
/home/shhh/2//def.c
/home/shhh/2//gthjrjrdj.c
/kernel/sssh/sarawtera.c
/kernel/sssh/wrawrt.h
/kernel/sssh/wearwaerw.h

回答1:


What you probably want is the following:

$ awk '/^\//{path=$0}/^[a-zA-Z]/ {printf("%s/%s\n",path,$0)}' file
/home/jhyoon//abc.c
/home/jhyoon/2//def.c
/home/jhyoon/2//gthjrjrdj.c
/kernel/sssh/sarawtera.c
/kernel/sssh/wrawrt.h
/kernel/sssh/wearwaerw.h

Explanation

  • /^\//{path=$0} on lines starting with a /, store it in the path variable.
  • /^[a-zA-Z]/ {printf("%s/%s\n",path,$0)} on lines starting with a letter, print the stored path together with the current line.

Note you can also say

awk '/^\//{path=$0; next} {printf("%s/%s\n",path,$0)}' file

Some comments

  • cat file | awk '...' is better written as awk '...' file.
  • You don't need the ; at the end of a block {} if you are executing just one command. It is implicit.


来源:https://stackoverflow.com/questions/27040142/processing-of-awk-with-multiple-variable-from-previous-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!