บทที่ 15
I/O Redirection (< , > , >>)
ตั้งแต่บทที่ 02 เป็นต้นมาจะเห็นว่าเราป้อนคำสั่งผ่านทางคีบอร์ดและแสดงผลออกมาทางหน้าจอ ซึ่งเจ้าคีบอร์ดและหน้าจอของเราก็คือ Input/Output Standard นั้นเอง
แต่เราสามารถที่จะเปลี่ยนทิศทาง (Redirection) จากรับ input ผ่านคีบอร์ดเป็นรับจาก file แทน หรือ เราจะเปลี่ยนทิศทางการแสดงผลจากหน้าจอเป็นการบันทึกลง text file แทนก็ได้..(เก่งจัง)
แบบฝึกหัด
1 $ cd ~/learncli
2 $ ls -F
3 cat.txt copydir/ fox.txt movedir/ right/ toolong.txt
4
5 $ cat fox.txt cat.txt
6 $ cat fox.txt cat.txt > foxcat.txt
7 $ cat cat.txt fox.txt > catfox.txt
8 $ ls
9 $ cat foxcat.txt
10 $ cat catfox.txt
11
12 $ cat > colors.txt
13 Red
14 Green
15 Blue
16 ^D <-- บรรทัดนี้หมายความว่าให้กดปุ่ม Ctrl+d นะครับ
17
18 $ cat colors.txt
19
20 $ cat > colors.txt
21 Black
22 White
23 Yellow
24 ^D
25
26 $ cat colors.txt
27
28 $ cat >> colors.txt
29 Red
30 Green
31 Blue
32 ^D
33
34 $ cat colors.txt
35
36 $ cat >> colors.txt
37 Pink
38 Purple
39 ^D
40
41 $ cat colors.txt
42
43 $ cat < colors.txt
44 $ more < colors.txt
45 $ less < colors.txt
46
47 $ sort < colors.txt
48 $ sort < colors.txt > sortcolors.txt
49 $ cat sortcolors.txt
บทนี้เรียนรู้อะไร?
- ’>’ เป็นการกำหนดให้ส่ง Output ไปยัง file ที่ระบุ ถ้า file ที่ระบุมีอยู่แล้วจะเป็นการเขียนข้อมูลทับ file เดิม
- ’<’ เป็นการกำหนดให้รับ Input จาก file ที่ระบุ
- ’>>’ เป็นการกำหนดให้ส่ง Output ไปยัง file ที่ระบุ ถ้า file ที่ระบุมีอยู่แล้วจะเป็นการเขียนข้อมูลต่อจากข้อมูลเดิม
เพิ่มเติม
- ลองเล่นผสมกันระหว่างการ Redirection และ Pipes ดูนะครับ