heaven4us
heaven4us

Reputation: 9

Processing of awk with multiple variable from previous processing?

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

Upvotes: 0

Views: 145

Answers (1)

fedorqui
fedorqui

Reputation: 290105

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.

Upvotes: 1

Related Questions