Matt
Matt

Reputation: 1032

setting the NR to 1 does not work (awk)

I have the following script in bash.

awk -F ":" '{if($1 ~ "^fall") 
                      { NR==1
                      {{printf "\t<course id=\"%s\">\n",$1} } } }' file1.txt > container.xml

So what I have a small file. If ANY line starts with fall, then I want the first field of the VERY first line.

So I did that in the code and set NR==1. However, it does not do the job!!!

Upvotes: 1

Views: 619

Answers (3)

Zombo
Zombo

Reputation: 1

#!awk -f
BEGIN {
  FS = ":"
}
NR==1 {
  foo = $1
}
/^fall/ {
  printf "\t<course id=\"%s\">\n", foo
}

Also note

BUGS The -F option is not necessary given the command line variable assignment feature; it remains only for backwards compatibility.

awk man page

Upvotes: 0

John1024
John1024

Reputation: 113864

Try this:

awk -F: 'NR==1 {id=$1} $1~/^fall/ {printf "\t<course id=\"%s\">\n",id}' file1.txt > container.xml

Notes:

  • NR==1 {id=$1}

    This saves the course ID from the first line

  • $1~/^fall/ {printf "\t<course id=\"%s\">\n",id}

    If any line begins with fall, then the course ID is printed.

  • The above code illustrates that awk commands can be preceded by conditions. Thus, id=$1 is executed only if we are on the first line: NR==1. If this way, it is often unnecessary to have explicit if statements.

  • In awk, assignment with done with = while tests for equality are done with ==.

If this doesn't do what you want, then please add sample input and corresponding desired output to the question.

Upvotes: 1

Kent
Kent

Reputation: 195139

awk -F: 'NR==1{x=$1}/^fail/{printf "\t<course id=\"%s\">\n",x;exit}' file

Note:

  • if the file has any line beginning with fail, print the 1st field in very first line in certain format (xml tag).
  • no matter how many lines with fail as start, it outputs the xml tag only once.
  • if the file has no line starts with fail, it outputs nothing.

Upvotes: 1

Related Questions