-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgetline.html
More file actions
1235 lines (828 loc) · 69.2 KB
/
getline.html
File metadata and controls
1235 lines (828 loc) · 69.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html lang="ko" >
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-161001174-3"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-161001174-3');
</script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>getline | Introduction</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="generator" content="GitBook 2.6.7">
<meta name="HandheldFriendly" content="true"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
<link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="gitbook/style.css">
<link rel="stylesheet" href="gitbook/plugins/gitbook-plugin-highlight/website.css">
<link rel="stylesheet" href="gitbook/plugins/gitbook-plugin-search/search.css">
<link rel="stylesheet" href="gitbook/plugins/gitbook-plugin-fontsettings/website.css">
<link rel="next" href="./arrays.html" />
<link rel="prev" href="./redirection.html" />
</head>
<body>
<div class="book"
data-level="8"
data-chapter-title="getline"
data-filepath="getline.md"
data-basepath="."
data-innerlanguage="">
<div class="book-summary">
<nav role="navigation">
<ul class="summary">
<li class="chapter " data-level="0" data-path="index.html">
<a href="./index.html">
<i class="fa fa-check"></i>
Introduction
</a>
</li>
<li class="chapter " data-level="1" data-path="bug_reports.html">
<a href="./bug_reports.html">
<i class="fa fa-check"></i>
<b>1.</b>
Bug reports
</a>
</li>
<li class="chapter " data-level="2" data-path="basics.html">
<a href="./basics.html">
<i class="fa fa-check"></i>
<b>2.</b>
Basics
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="data_types.html">
<a href="./data_types.html">
<i class="fa fa-check"></i>
<b>2.1.</b>
Data Types
</a>
</li>
<li class="chapter " data-level="2.2" data-path="variables.html">
<a href="./variables.html">
<i class="fa fa-check"></i>
<b>2.2.</b>
Variables
</a>
</li>
<li class="chapter " data-level="2.3" data-path="regex.html">
<a href="./regex.html">
<i class="fa fa-check"></i>
<b>2.3.</b>
Regex
</a>
</li>
<li class="chapter " data-level="2.4" data-path="functions.html">
<a href="./functions.html">
<i class="fa fa-check"></i>
<b>2.4.</b>
Functions
</a>
</li>
<li class="chapter " data-level="2.5" data-path="escape_sequences.html">
<a href="./escape_sequences.html">
<i class="fa fa-check"></i>
<b>2.5.</b>
Escape sequences
</a>
</li>
<li class="chapter " data-level="2.6" data-path="begin_end.html">
<a href="./begin_end.html">
<i class="fa fa-check"></i>
<b>2.6.</b>
BEGIN, END
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="3" data-path="builtin_variables.html">
<a href="./builtin_variables.html">
<i class="fa fa-check"></i>
<b>3.</b>
Built-in Variables
</a>
</li>
<li class="chapter " data-level="4" data-path="record_sep.html">
<a href="./record_sep.html">
<i class="fa fa-check"></i>
<b>4.</b>
Record 분리
</a>
</li>
<li class="chapter " data-level="5" data-path="field_sep.html">
<a href="./field_sep.html">
<i class="fa fa-check"></i>
<b>5.</b>
Field 분리
</a>
</li>
<li class="chapter " data-level="6" data-path="zero_one.html">
<a href="./zero_one.html">
<i class="fa fa-check"></i>
<b>6.</b>
$0=$0, $1=$1
</a>
</li>
<li class="chapter " data-level="7" data-path="redirection.html">
<a href="./redirection.html">
<i class="fa fa-check"></i>
<b>7.</b>
Redirection
</a>
</li>
<li class="chapter active" data-level="8" data-path="getline.html">
<a href="./getline.html">
<i class="fa fa-check"></i>
<b>8.</b>
getline
</a>
</li>
<li class="chapter " data-level="9" data-path="arrays.html">
<a href="./arrays.html">
<i class="fa fa-check"></i>
<b>9.</b>
Arrays
</a>
<ul class="articles">
<li class="chapter " data-level="9.1" data-path="sort.html">
<a href="./sort.html">
<i class="fa fa-check"></i>
<b>9.1.</b>
Sort
</a>
</li>
<li class="chapter " data-level="9.2" data-path="GROUP_BY.html">
<a href="./GROUP_BY.html">
<i class="fa fa-check"></i>
<b>9.2.</b>
GROUP BY
</a>
</li>
<li class="chapter " data-level="9.3" data-path="JOIN.html">
<a href="./JOIN.html">
<i class="fa fa-check"></i>
<b>9.3.</b>
JOIN
</a>
</li>
<li class="chapter " data-level="9.4" data-path="subquery.html">
<a href="./subquery.html">
<i class="fa fa-check"></i>
<b>9.4.</b>
Subquery
</a>
</li>
<li class="chapter " data-level="9.5" data-path="index2.html">
<a href="./index2.html">
<i class="fa fa-check"></i>
<b>9.5.</b>
Index
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="10" data-path="control_statements.html">
<a href="./control_statements.html">
<i class="fa fa-check"></i>
<b>10.</b>
Control Statements
</a>
</li>
<li class="chapter " data-level="11" data-path="operators.html">
<a href="./operators.html">
<i class="fa fa-check"></i>
<b>11.</b>
Operators
</a>
</li>
<li class="chapter " data-level="12" data-path="builtin_functions.html">
<a href="./builtin_functions.html">
<i class="fa fa-check"></i>
<b>12.</b>
Built-in Functions
</a>
<ul class="articles">
<li class="chapter " data-level="12.1" data-path="builtin/numeric.html">
<a href="./builtin/numeric.html">
<i class="fa fa-check"></i>
<b>12.1.</b>
Numeric Functions
</a>
</li>
<li class="chapter " data-level="12.2" data-path="builtin/string.html">
<a href="./builtin/string.html">
<i class="fa fa-check"></i>
<b>12.2.</b>
String Functions
</a>
</li>
<li class="chapter " data-level="12.3" data-path="builtin/io.html">
<a href="./builtin/io.html">
<i class="fa fa-check"></i>
<b>12.3.</b>
I/O Functions
</a>
</li>
<li class="chapter " data-level="12.4" data-path="builtin/time.html">
<a href="./builtin/time.html">
<i class="fa fa-check"></i>
<b>12.4.</b>
Time Functions
</a>
</li>
<li class="chapter " data-level="12.5" data-path="builtin/bitwise.html">
<a href="./builtin/bitwise.html">
<i class="fa fa-check"></i>
<b>12.5.</b>
Bitwise Functions
</a>
</li>
<li class="chapter " data-level="12.6" data-path="builtin/type.html">
<a href="./builtin/type.html">
<i class="fa fa-check"></i>
<b>12.6.</b>
Type Functions
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="13" data-path="extensions.html">
<a href="./extensions.html">
<i class="fa fa-check"></i>
<b>13.</b>
Dynamic Extensions
</a>
<ul class="articles">
<li class="chapter " data-level="13.1" data-path="example.html">
<a href="./example.html">
<i class="fa fa-check"></i>
<b>13.1.</b>
예제
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="14" data-path="tcp_ip.html">
<a href="./tcp_ip.html">
<i class="fa fa-check"></i>
<b>14.</b>
TCP/IP Internetworking
</a>
</li>
<li class="chapter " data-level="15" data-path="command_line_options.html">
<a href="./command_line_options.html">
<i class="fa fa-check"></i>
<b>15.</b>
Command-line options
</a>
</li>
<li class="chapter " data-level="16" data-path="debugging.html">
<a href="./debugging.html">
<i class="fa fa-check"></i>
<b>16.</b>
Debugging
</a>
</li>
<li class="chapter " data-level="17" data-path="tips.html">
<a href="./tips.html">
<i class="fa fa-check"></i>
<b>17.</b>
Tips
</a>
</li>
<li class="divider"></li>
<li>
<a href="https://www.gitbook.com" target="blank" class="gitbook-link">
</a>
</li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<!-- Actions Left -->
<!-- Title -->
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i>
<a href="./" >Introduction</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<section class="normal" id="section-">
<h1 id="getline">getline</h1>
<p>Awk 의 장점 중에 하나가 입, 출력 하는 방법이 간단하다는 것입니다.
프로그래밍 언어에서처럼 open 함수를 사용하고 할 필요 없이
redirection 과 getline 만을 이용해서 간단히 처리할 수가 있습니다.
이 방법은 shell 에서 사용하는 방법과 비슷하므로 기존에 shell 에 대한 지식이 있으면
어렵지 않게 바로 사용할 수가 있습니다.</p>
<p>awk 에서 파일을 읽어들일 때는 꼭 명령 라인에서 인수로 전달한 파일만 사용할 수 있는 것은 아닙니다.
메인 입력 스트림과 별개로 시스템 내 어떤 파일이라도 코드 내에서 단독으로 입,출력할 수 있습니다.</p>
<p>그리고 이름이 getline 이라고 해서 입력을 라인 단위로 하지 않습니다.
awk 는 항상 레코드 단위입니다.
명령 사이클에 의해 메인 입력 스트림으로부터 읽어 들이던 redirection 을 이용해
직접 읽어들이던 상관 없이 항상 RS, FS 가 적용됩니다.
( getline var 형식은 FS 적용에서 제외. )</p>
<blockquote>
<p>pipe 나 coprocess 도 모두 redirection 에 포함되는 개념입니다.</p>
</blockquote>
<h3 id="read-from-main-input-stream">read from main input stream</h3>
<table>
<thead>
<tr>
<th>Variant</th>
<th>Effect</th>
</tr>
</thead>
<tbody>
<tr>
<td>getline</td>
<td>Sets <code>$0</code>, <code>NF</code>, <code>$1</code>, <code>$2</code> ..., <code>FNR</code>, <code>NR</code>, and <code>RT</code></td>
</tr>
<tr>
<td>getline var</td>
<td>Sets <code>var</code>, <code>FNR</code>, <code>NR</code>, and <code>RT</code></td>
</tr>
</tbody>
</table>
<p>getline 문에 아무런 redirection 기호가 사용되지 않으면 디폴트는 메인 입력 스트림에서
레코드를 읽어 들입니다.
awk 가 명령 사이클을 시작할 때 기본적으로 읽어들이는 스트림입니다.
위 테이블에서 오른쪽에 나열된 변수들이 getline 명령이 실행됐을 때 설정되는 변수들입니다.</p>
<p>getline 명령을 단독으로 사용하면 읽어들인 레코드를 <code>$0</code> 변수에 대입합니다.
<code>$0</code> 변수에 대입 연산이 일어나므로 <code>NF</code> 값과 필드 변수값들이( $1, $2, $3... ) 재설정 되고
레코드를 새로 읽어 들였으므로 <code>NR</code>, <code>FNR</code> 값이 변경됩니다.
마지막으로 레코드를 읽어 들일 때 <code>RS</code> 값에 의해 매칭 된 구분자가 <code>RT</code> 변수에 설정됩니다.</p>
<p>getline 명령에 <code>var</code> 변수를 사용하게 되면 읽어들인 레코드 값이 <code>$0</code> 변수에 대입되지 않고
<code>var</code> 변수에 대입됩니다.
따라서 이때는 <code>$0</code>, <code>NF</code> 와 필드 변수들은 변경되지 않고 기존의 값을 그대로 유지합니다.</p>
<h2 id="read-file">read file</h2>
<table>
<thead>
<tr>
<th>Variant</th>
<th>Effect</th>
</tr>
</thead>
<tbody>
<tr>
<td>getline < "file"</td>
<td>Sets <code>$0</code>, <code>NF</code>, <code>$1</code>, <code>$2</code> ... and <code>RT</code></td>
</tr>
<tr>
<td>getline var < "file"</td>
<td>Sets <code>var</code> and <code>RT</code></td>
</tr>
</tbody>
</table>
<p>이것은 메인 입력 스트림으로부터 레코드를 읽어들이는 것이 아니라 redirection 기호를 이용해서
지정한 파일로부터 레코드를 읽어들이는 것입니다.
<code>NR</code>, <code>FNR</code> 값은 메인 입력 스트림에서 읽어들일 때만 변경되므로 Effect 컬럼에서 제외되었습니다.
getline 명령에 변수를 사용하지 않으면 읽어들인 레코드 값이 <code>$0</code> 에 대입되고 <code>NF</code> 와 필드 변수값들이
설정 됩니다.</p>
<p>getline 명령에 <code>var</code> 변수를 사용하게 되면 <code>var</code> 변수와 <code>RT</code> 변수값만 변경됩니다.</p>
<pre><code class="lang-bash">$ cat file1
num x:
num y:
num z:
$ cat file2
<span class="hljs-number">111</span> <span class="hljs-number">222</span> <span class="hljs-number">333</span>
<span class="hljs-number">444</span> <span class="hljs-number">555</span> <span class="hljs-number">666</span>
<span class="hljs-number">777</span> <span class="hljs-number">888</span> <span class="hljs-number">999</span>
$ awk <span class="hljs-string">'BEGIN { while (getline $1 < "file1" && getline $2 < "file2") print }'</span>
num x: <span class="hljs-number">111</span> <span class="hljs-number">222</span> <span class="hljs-number">333</span>
num y: <span class="hljs-number">444</span> <span class="hljs-number">555</span> <span class="hljs-number">666</span>
num z: <span class="hljs-number">777</span> <span class="hljs-number">888</span> <span class="hljs-number">999</span>
$ awk <span class="hljs-string">'{ getline $(NF+1) < "file2"; print }'</span> file1
num x: <span class="hljs-number">111</span> <span class="hljs-number">222</span> <span class="hljs-number">333</span>
num y: <span class="hljs-number">444</span> <span class="hljs-number">555</span> <span class="hljs-number">666</span>
num z: <span class="hljs-number">777</span> <span class="hljs-number">888</span> <span class="hljs-number">999</span>
$ awk <span class="hljs-string">'BEGIN {
while (1) {
if ( ! getline < "file1" ) exit
v1 = $2
if ( ! getline < "file2" ) exit
v2 = $3
print v1 " " v2
}
}'</span>
x: <span class="hljs-number">333</span>
y: <span class="hljs-number">666</span>
z: <span class="hljs-number">999</span>
</code></pre>
<h2 id="pipe">pipe</h2>
<table>
<thead>
<tr>
<th>Variant</th>
<th>Effect</th>
</tr>
</thead>
<tbody>
<tr>
<td>"command" | getline</td>
<td>Sets <code>$0</code>, <code>NF</code>, <code>$1</code>, <code>$2</code> ... and <code>RT</code></td>
</tr>
<tr>
<td>"command" | getline var</td>
<td>Sets <code>var</code> and <code>RT</code></td>
</tr>
</tbody>
</table>
<p>외부 명령이 실행될 때는 <code>sh -c</code> 형태로 실행되므로
기존에 shell 에서 명령을 작성할때 처럼 파이프를 이용해 여러 명령을
연결할 수도 있고 redirection 을 사용할 수도 있습니다.
"command" 실행 결과는 shell 에서처럼 <code>stdout</code> 출력이 파이프를 통해 getline 에 전달됩니다.</p>
<p><img src="images/getline_pipe.png" alt=""></p>
<pre><code class="lang-bash">$ awk <span class="hljs-string">'
BEGIN {
if ( "pidof chrome | xargs -n1 | wc -l" | getline count )
print "total chrome pids : " count
}'</span>
<span class="hljs-number">45</span>
-----------------------------------------------
$ awk <span class="hljs-string">'BEGIN {
while ( "sort /proc/modules" | getline > 0 )
print $1
}'</span>
-----------------------------------------------
$ <span class="hljs-built_in">echo</span> <span class="hljs-string">"333 111 444 222"</span> |
awk <span class="hljs-string">'{
for (i=1; i<=NF; i++)
print $i | "sort > file"
}'</span>
$ cat file
<span class="hljs-number">111</span>
<span class="hljs-number">222</span>
<span class="hljs-number">333</span>
<span class="hljs-number">444</span>
</code></pre>
<h2 id="coprocess-">coprocess (<code>|&</code>)</h2>
<table>
<thead>
<tr>
<th>Variant</th>
<th>Effect</th>
</tr>
</thead>
<tbody>
<tr>
<td>"command" |& getline</td>
<td>Sets <code>$0</code>, <code>NF</code>, <code>$1</code>, <code>$2</code> ... and <code>RT</code></td>
</tr>
<tr>
<td>"command" |& getline var</td>
<td>Sets <code>var</code> and <code>RT</code></td>
</tr>
</tbody>
</table>
<p>파이프를 이용하면 외부 명령의 실행 결과를 getline 으로 받을 수도 있고
또한 프린트 문을 이용해 데이터를 외부 명령에 전달할 수도 있는데요.
하지만 이것은 데이터가 단 방향으로 만 전달되는 것입니다.
이 두 가지 기능을 합쳐서 외부 명령에 데이터를 전달하고,
다시 외부 명령의 실행 결과를 getline 으로 받을 수 있는 것이 coprocess 입니다.
coprocess 는 외부 명령과 양방향 통신이 필요할 때 사용할 수 있는 기능입니다.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># 프린트문으로 외부 명령에 데이터를 전달하고 실행 결과를 getline 으로 받을 수 있습니다.</span>
<span class="hljs-built_in">print</span> <span class="hljs-string">"SELECT id, name, price ..."</span> |& <span class="hljs-string">"db_server"</span>
<span class="hljs-string">"db_server"</span> |& getline
<span class="hljs-comment"># 파이프는 단방향 통신으로 date 명령이 /bin/sh 에 전달되어 실행 결과가 stdout 으로 출력</span>
$ awk <span class="hljs-string">'BEGIN {
print "date" | "/bin/sh"
}'</span>
Fri Jun <span class="hljs-number">30</span> <span class="hljs-number">18</span>:<span class="hljs-number">22</span>:<span class="hljs-number">10</span> KST <span class="hljs-number">2017</span>
<span class="hljs-comment"># 다음과 같이 하면 date 명령의 실행 결과가 stdout 으로 출력되지 않고 getline 으로 받을 수 있다.</span>
$ awk <span class="hljs-string">'BEGIN {
print "date" |& "/bin/sh"
"/bin/sh" |& getline v
print v
}'</span>
Fri Jun <span class="hljs-number">30</span> <span class="hljs-number">18</span>:<span class="hljs-number">51</span>:<span class="hljs-number">42</span> KST <span class="hljs-number">2017</span>
</code></pre>
<p>shell 에서처럼 두 개의 외부 명령을 직접 연결해 사용할 수 없습니다.
항상 중간에 awk 를 거쳐야 합니다.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Wrong !!</span>
<span class="hljs-string">"ls -1"</span> | <span class="hljs-string">"wc -l"</span>
<span class="hljs-comment"># Wrong !!</span>
<span class="hljs-string">"ls -1"</span> |& <span class="hljs-string">"wc -l"</span>
<span class="hljs-comment"># OK</span>
$ awk <span class="hljs-string">'BEGIN {
while ("ls -1" | getline v) print v |& "wc -l"
close("wc -l", "to")
"wc -l" |& getline v
print v
}'</span>
<span class="hljs-number">6</span>
</code></pre>
<h3 id="getline-명령과-종료-상태-값">getline 명령과 종료 상태 값</h3>
<p>getline 명령은 새로운 레코드를 읽어들이는 것이 성공했을 경우 <code>1</code> 이 반환되고
그렇지 않을 경우는 <code>0</code> 이 반환됩니다 ( End Of File ).
그 외에 파일이 존재하지 않거나, 읽을 권한이 없거나 하는 경우는 <code>-1</code> 이 반환됩니다.
<code>0</code> 이외의 값은 참이 되므로 만약에 첫 번째와 같이 작성할 경우
파일이 존재하지 않는다면 무한 루프에 빠지게 되겠죠.
따라서 두 번째와 같이 체크해야 합니다.</p>
<pre><code class="lang-bash"><span class="hljs-number">1</span>. <span class="hljs-keyword">while</span> ( getline < <span class="hljs-string">"file.txt"</span> ) ...
<span class="hljs-number">2</span>. <span class="hljs-keyword">while</span> ( (getline < <span class="hljs-string">"file.txt"</span>) > <span class="hljs-number">0</span> ) ...
<span class="hljs-comment"># 반환값을 체크할 때 ( ) 는 생략할 수 있습니다.</span>
<span class="hljs-number">3</span>. <span class="hljs-keyword">while</span> ( getline < <span class="hljs-string">"file.txt"</span> > <span class="hljs-number">0</span> ) ...
</code></pre>
<p>또한 레코드 읽기에 실패하여 <code>0</code> 이 반환될 경우는
이전 <code>$0</code> 값이 변경되지 않고 그대로 남아있게 되므로
성공 여부를 체크해야 합니다.</p>
<pre><code class="lang-bash">$ cat file.txt
<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span> <span class="hljs-comment"># 2 개의 레코드</span>
a,b,c,d,e,f,g,h,i
<span class="hljs-comment"># 세 번째 getline 부터 사실상 레코드 읽기가 실패하여 이전 $0 값이 프린트된다.</span>
$ awk <span class="hljs-string">'BEGIN{ for ( i=0; i<5; i++ ) { getline < "file.txt"; print } }'</span>
<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>
a,b,c,d,e,f,g,h,i
a,b,c,d,e,f,g,h,i
a,b,c,d,e,f,g,h,i
a,b,c,d,e,f,g,h,i
<span class="hljs-comment"># 따라서 다음과 같이 반환값을 체크해서 사용해야 합니다.</span>
$ awk <span class="hljs-string">'BEGIN{ for ( i=0; i<5; i++ ) { if (getline < "file.txt") print } }'</span>
<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>
a,b,c,d,e,f,g,h,i
</code></pre>
<p>getline 이 파이프와 함께 사용될 경우는 명령의 존재 여부나 성공에 상관없이
출력값의 유, 무에 따라 <code>1</code> 또는 <code>0</code> 이 반환되므로 다음과 같이 체크하면 됩니다.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">while</span> ( command... | getline ) ....
</code></pre>
<p>명령 실행 결과 아무런 출력이 발생하지 않았다는 것은
명령이 정상적으로 실행되지 않은 것으로 판단할 수 있습니다.
이것은 외부 명령의 종료 상태 값과는 관계가 없는 것으로
단지 <code>stdout</code> 출력의 유, 무를 가지고 판단하는 것입니다.</p>
<pre><code class="lang-bash">$ awk <span class="hljs-string">'BEGIN {
cmd = "stat -c %s foobar" # foobar 는 존재하지 않는 파일
if ( cmd | getline var )
print "OK: " var
else
print "Error: " cmd
}'</span>
<span class="hljs-built_in">stat</span>: cannot <span class="hljs-built_in">stat</span> <span class="hljs-string">'foobar'</span>: No such file or directory <span class="hljs-comment"># stat 명령의 stderr 출력 메시지</span>
Error: <span class="hljs-built_in">stat</span> -c %s foobar
<span class="hljs-comment"># 다음과 같은 경우 stat 명령이 오류로 종료하였지만 2>&1 를 이용해</span>
<span class="hljs-comment"># stderr 출력을 stdout 로 redirect 하여 getline 명령에서 OK 가 출력됩니다.</span>
$ awk <span class="hljs-string">'BEGIN {
cmd = "stat -c %s foobar 2>&1"
if ( cmd | getline var )
print "OK: " var
else
print "Error: " cmd
}'</span>
OK: <span class="hljs-built_in">stat</span>: cannot <span class="hljs-built_in">stat</span> <span class="hljs-string">'foobar'</span>: No such file or directory
</code></pre>
<p>Socket 이나 <a href="tips.html#timeout">READ_TIMEOUT</a> 기능을 사용할 때는 <code>-1</code> 이 반환될 수 있습니다.<br><code>-1</code> 이 반환될 때는 ERRNO 변수값도 함께 설정됩니다.</p>
<pre><code class="lang-bash">$ awk <span class="hljs-string">'BEGIN {
service = "/inet/tcp/0/0.0.0.0/daytime"
print ( getline < service )
print "ERRNO: " ERRNO
}'</span>
-<span class="hljs-number">1</span>
ERRNO: Address family not supported by protocol
$ awk <span class="hljs-string">'BEGIN {
PROCINFO["/dev/stdin", "READ_TIMEOUT"] = 2000 # 2 초
print ( getline var < "/dev/stdin" )
print "ERRNO: " ERRNO
}'</span>
-<span class="hljs-number">1</span>
ERRNO: Connection timed out
</code></pre>
<p><a name="close"></a></p>
<h2 id="close-함수">close 함수</h2>
<p>redirection 에 의해 open 된 파일, 명령 리소스는 awk 명령이 실행을 종료하게 되면 자동으로 반환됩니다.
하지만 명령 실행중에는 한번 open 되면 종료될 때까지 open 상태를 유지하므로
경우에 따라서 close 함수를 이용해 관리를 해주어야 합니다.
close 함수는 리소스를 반환하는 역할 외에도 파일 포지션과 파이프에 연결된 외부 명령 실행을
컨트롤할 수 있는 기능이 있습니다.</p>
<ul>
<li><p>앞서 읽어들인 파일을 처음부터 다시 읽어들여야 할 때<br>파일이나 파이프로부터 레코드를 읽어들이는 중에 다시 처음부터 읽어들여야 할 때</p>
</li>
<li><p>파이프로 연결된 외부 명령이 바로 실행되어야 할 때</p>
</li>
<li><p>coprocess 로 연결된 외부 명령의 실행이 정상적으로 진행되고 종료되어야 할 때</p>
</li>
<li><p>print, <code>></code>, <code>>></code> 를 이용해 출력한 내용이 실제 파일에 쓰기 완료되어야 할 때</p>
</li>
</ul>
<p>다음 함수는 아무 문제가 없어 보이는데요. 실제 두 가지 문제를 가지고 있습니다.
첫 번째는 매번 함수가 실행될 때마다 파일명이 바뀌기 때문에 새로운 명령 리소스가 계속해서 생성되는 것이고
두 번째는 만약에 이전에 한번 체크에 사용했던 파일명이 다시 사용될 경우
값이 출력되지 않는다는 점입니다.
왜냐하면 처음 파일이 사용될 때 파이프가 오픈된 상태라서
명령 실행 결과를 나타내는 파일 포지션이 다음 라인을 가리키고 있기 때문입니다.
<code>file</code> 외부 명령은 실행 결과로 하나의 라인만 출력하므로 다음 라인을 읽을 경우
아무 값도 나타나지 않겠죠.
따라서 다음과 같은 경우는 반드시 close 함수를 사용해야 합니다.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">function</span> getFileType(file, cmd, <span class="hljs-built_in">type</span>) {
cmd = <span class="hljs-string">"file -b --mime-type "</span> file
cmd | getline <span class="hljs-built_in">type</span>
<span class="hljs-built_in">return</span> <span class="hljs-built_in">type</span>