管道 | 和重定向符

1. 管道 |

管道|就是用來將符號|前的命令輸出作爲符號後命令的輸入,多個命令的順序一定是從左到右順序執行,下面用幾個例子來解釋。

  • ps aux | grep chrome: 查看chrome瀏覽器的進程信息。利用ps aux獲取的結果,在結果裏搜索帶chrome字段的行就可以得到chrome進程信息。
➜  linux_commands ps aux | grep chrome
qiushye          30641   0.0  0.0  4268280    548 s000  R+   12:12PM   0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn chrome
qiushye            598   0.0  0.0  4308152    256   ??  S    24Mar20   0:01.46 /Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Framework.framework/Versions/80.0.3987.149/Helpers/chrome_crashpad_handler --monitor-self-annotation=ptype=crashpad-handler --database=/Users/qiushye/Library/Application Support/Google/Chrome/Crashpad --metrics-dir=/Users/qiushye/Library/Application Support/Google/Chrome --url=https://clients2.google.com/cr/report --annotation=channel= --annotation=plat=OS X --annotation=prod=Chrome_Mac --annotation=ver=80.0.3987.149 --handshake-fd=7
  • ls | wc -l: 查看當前目錄下的文件和目錄個數
➜  linux_commands ls | wc -l
      11
➜  linux_commands ls
diff.txt  input.txt sl_test4  test1     test4     ut
head.txt  ls.txt    sl_ut     test3     tt
  • grep d test3 | grep o: 在test3文件中找出既帶"d"又帶"o"的行
➜  linux_commands cat test3
hello world!


oh my god!
你是

ss
➜  linux_commands grep d test3 | grep o
hello world!
oh my god!
  • ls | sort: 對目錄下的文件按名稱排序展示
➜  linux_commands ls | sort
diff.txt
head.txt
input.txt
ls.txt
sl_test4
sl_ut
test1
test3
test4
tt
ut

2. 重定向>, >>, <

2.1 command > file: 將命令command的輸出重定向到文件file中

  • echo [text] > [file]: 將一段文本內容[text]寫入文件[file]中
➜  linux_commands echo "ls" > ls.cmd
➜  linux_commands cat ls.cmd
ls
  • cat [file1] > [file2]: 將文件[file1]的內容寫入到文件[file2]中
➜  linux_commands ls test5
ls: test5: No such file or directory
➜  linux_commands cat test1 > test5
➜  linux_commands diff test1 test5
➜  linux_commands ls -l test1 test5 (只複製內容,元數據獨立)
-rwxrwxrwx  1 qiushye  staff  47 Apr  4 22:24 test1
-rw-r--r--  1 qiushye  staff  47 Apr 10 12:40 test5
  •  grep [text] [file1] > [file2]: 將文件[file1]查找文本[text]的行寫入到文件[file2]中
➜  linux_commands grep o test1 > test6
➜  linux_commands cat test6
hello world!
oh my god!

2.2 comand >> file: 將命令command的輸出以追加的方式重定向到文件file中

  • echo [text] >> [file]: 將一段文本內容[text]追加寫入文件[file]中
➜  linux_commands cat ls.cmd
ls
➜  linux_commands echo "ls -l" >> ls.cmd
➜  linux_commands cat ls.cmd
ls
ls -l
  • cat, grep或其他命令也是類似,此處不多展示,用法和>類似 

2.3 command < file: 將命令command的輸入重定向到file,即以file作爲command的輸入

  • cat < [file] == cat [file]
➜  linux_commands cat < ls.cmd
ls
ls -l
  • grep [text] < [file1] > [file2]: 將文件[file1]中查找文本[text]的行寫入文件[file2]中
➜  linux_commands grep h < test1 > test7
➜  linux_commands cat test7
hello world!
oh my god!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章