I think it is because you are always printing a value. So, you are not over-writing 'a' ni the instance of the 4th line, so when you print the variable, you are getting the last stored value of 'a'.
Perhaps as the first line ater your else, do a
Thanks, I know in this example I gave, egrep is a better choice, but actually my real work is "finding out both "user" and "nas" part, and then print out the result.
below is the result I want
+
user_a nas_b
user_d nas_b
user_a
user_c nas_m
+
But the problem is, no matter how i modified my script, I just won't get the desired result...
[quote=radoulov;302286540]
With awk:
awk '{
for (i=1; i<=NF; i++)
if ($i ~ /user/)
print $i
}' infile
an actual (with blah-s) file sample would be helpful. A desired output (based on a sample input) would not hurt either.
Please use vB Codes when posting samples/quotes.
$more /tmp/test
user_a blabla nas_b
blabla nas_b blabla user_d
this is a user_a
another junk line
user_c nas_m blabla
please note, user and nas may or may not appear on each line, and the position of user and nas are not fixed, they can appear in any column.
I need a script to scan each line, if any line contains user or nas, or both, they will be extracted from the line and be printed out, and i want print user before nas if a line has both words. in my case, the result will be look like:
user_a nas_b
user_d nas_b
user_a
user_c nas_m
I tried to monky with awk for a while, but just can not figure out a good way to make it.
sorry, one more question, I have been trying to read some awk documents, but apparently the time is just not enough for me to pick up the awk "array" very quickly. Right now I just saved the script.
If I insert one more keyword group into the test file, how can i tune this awk script to pick up all 3 keywords and print user first, nas second and group last?
exmple,
$more /tmp/test
user_a blabla nas_b group_a
blabla nas_b group_b blabla user_d
this is a user_a, group_c
another junk line
group_d user_c nas_m blabla
Thanks for answering my question, I greatly appreciated! but the output is not 100% I want, see the last line, nas_m is on the last column. while i want all the nas show up on the second column.
awk '/user|nas|group/{ for (i=1; i<=NF; i++) {
if ($i ~ /user/) printf $i FS
if ($i ~ /nas/) a=$i
if ($i ~ /group/) b=$i }
for (j in a) printf a[j] FS
for (j in b) printf b[j] FS
print "" ; split("",a); split("",b) }' file