Reputation: 1032
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
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.
Upvotes: 0
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
Reputation: 195139
awk -F: 'NR==1{x=$1}/^fail/{printf "\t<course id=\"%s\">\n",x;exit}' file
Note:
fail
, print the 1st field in very first line in certain format (xml tag).fail
as start, it outputs the xml tag only once.fail
, it outputs nothing.Upvotes: 1