I have a file with a list of info. Each line has either 12 or 13 fields. For example I will use a file will 3 and 4 fields.

e.g. myfile.txt
user password location date
john passwd1  new_york today
     passwd2  london   yesterday
jeff passwd3  new_york tomorrow

I am looking for a way that would take johns name and copy it to the next line in the blank space.

so far I am trying something like:

Awk '{{if(NF==4) print $0; name=$1}; if(NF==3) print $name,$0}' ./myfile.txt >> ./my_editedfile.txt.

Every time I try, however, it either prints the literal $1, nothing, or the first field of the next line twice. i.e. line two will look like on of the following;

$1 passwd2 london yesterday
passwd2 london yesterday
passwd2 passwd2 london yesterday

Can someone help to set a variable on one line and then use it to print on the following one?

  • Try it with print name, $0... – jasonwryan Sep 2 '15 at 1:52
  • If I try that it will either print the literal $1 or nothing at all – Xentrees Sep 2 '15 at 1:57
  • 1
    awk '{if (NF==4) name=$1}; {print (NF==3) ? name $0 : $0 }' file – jasonwryan Sep 2 '15 at 2:32
  • I wasn't sure how this worked. what is the ? and the : for? This looks like it could be really useful in other projects I am working on. – Xentrees Sep 2 '15 at 2:59
  • It's the ternary operator. – jasonwryan Sep 2 '15 at 3:01

You are pretty close. You don't need the comma or the $ before your variable. Try:

awk '{if (NF == 4) {print $0; name=$1} else {print name$0}}'
  • Ah! this works. The issue was the brackets. I was using {{if()}} changing it to {if(){}} worked perfectly! the Full code was sed -e 's/\t/_/g' -e 's/\( *\) /_/g' /var/tmp/all_disks | awk -F ":|=|_" '/Reallocated/ {if(NF==13){ print $1,$6,$13; name=$1}; if(NF==12) print name,$5,$12}' > /var/tmp/suspect_disks – Xentrees Sep 2 '15 at 2:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.