linux 基础之-入门(基础命令)

Part one - 基础命令

1、命令

  1. date

  2. cal -calendar

  3. df -current amount of free space on your disk drives

  4. free -display the amount of free memory

  5. exit -closing the terminal emulator window

  6. crontab 定时任务
    通过crontab 命令,我们可以在固定的间隔时间执行指定的系统指令或 shell script脚本。时间间隔的单位可以是分钟、小时、日、月、周及以上的任意组合。这个命令非常适合周期性的日志分析或数据备份等工作。
    crontab的文件格式:分 时 日 月 星期 要运行的命令

    第1列分钟0~59
    第2列小时0~23(0表示子夜)
    第3列日1~31
    第4列月1~12
    第5列星期0~7(0和7表示星期天)
    第6列要运行的命令

    * * * * * echo "hello" #每1分钟执行hello
    3,15 * * * * myCommand #每小时第三分钟和第十五分钟执行
    3,15 8-11 * * * myCommand# 在上午8点到11点的第3和第15分钟执行
    3,15 8-11 */2  *  * myCommand #每隔两天的上午8点到11点的第3和第15分钟执行
    30 21 * * * /etc/init.d/smb restart #每晚的21:30重启smb
    0 23 * * 6 /etc/init.d/smb restart #每星期六的晚上11 : 00 pm重启smb
    

    注意事项:
    新创建的cron job,不会马上执行,至少要过2分钟才执行。如果重启cron则马上执行。

    当crontab失效时,可以尝试/etc/init.d/crond restart解决问题。或者查看日志看某个job有没有执行/报错tail -f /var/log/cron。

    $service cron restart
    

2、导航

  1. pwd - Print name of current working directory
  2. cd - Change directory
  3. ls - List directory contents
  4. file – Determine file type
  5. less – View file contents(和cat的区别?参考)

4 文件与目录

  1. cp #如果文件已经存在,直接覆盖,没有提示,要提示用-i
  2. mv
  3. mkdir
  4. rm # Remove Files And Directories
  5. ln # Create Links,软链接”和“硬链接”的区别:硬链接指向磁盘区块,软链接指向绝对路径。

hard links的缺点:

  1. cannot span physical devices.
  2. cannot reference directories, only files.

5 使用命令

  1. type – Indicate how a command name is interpreted

  2. which – Display An Executable’s Location

  3. help – Get help for shell builtins

     help cd
     cd: cd [-L|[-P [-e]] [-@]] [dir]
     Change the shell working directory.
    

    理解注释:[]是可选,|是互斥。

  4. -help – Display Usage Information

  5. man – Display a command’s manual page

  6. info – Display a command’s info entry

    man .info .–help 的用法和区别:help最简单,info最详细,man在两者之间。

  7. apropos – Display a list of appropriate commands

  8. whatis – Display a very brief description of a command

  9. alias – Create an alias for a command

    使用:

    #起别名前先检查是否存在,用type:
    tsc@tsc:~$ type test
    test is a shell builtin
    
    alias name='string' # name后不能有空格
    tsc@tsc:~$ alias foo='cd /usr; ls; cd -'
    tsc@tsc:~$ foo
    

    终端关闭后作用就消失了。

  10. unalias --去除别名

6 重定向

  1. cat - Concatenate files

    # cat file1 # 输出文件到屏幕,没有分页
    cat > file.txt # cat没有参数时接受stdin*
    this is test.
    # ctrl+d 结束*
    # < 接受文件输入*
    tsc@tsc:~$ cat < lazy_dog.txt
    
  2. sort - Sort lines of text

  3. uniq - Report or omit repeated lines

    # -d 显示重复的
    tsc@tsc:~$ ls /bin /usr/bin | sort | uniq -d | less
    
  4. grep - Print lines matching a pattern

    #“global regular expression print”,find功能。
    tsc@tsc:~$ ls /bin /usr/bin | sort | uniq | grep zip
    
  5. wc - Print newline, word, and byte counts for each file

    #联合使用看条目个数:
    tsc@tsc:~$ ls /bin /usr/bin | sort | uniq | wc -l
    
  6. head - Output the first part of a file

  7. tail - Output the last part of a file

  8. tee - Read from standard input and write to standard output and files

    这个名字很有意思,tee有三通管的意思,配合pipe使用,它的作用是从stdin读入,复制到stdout和文件。

    # 一方面输出到ls.txt,一方面传给grep
    tsc@tsc:~$ ls /usr/bin/ | tee ls.txt | grep zip
    

I/O redirection 的作用

I/O redirection allows us to change where output goes and where input comes from.

>重定向

tsc@tsc:~$ ls -l /usr/bin/ > ls-output.txt
tsc@tsc:~$ > ls-output2.txt  # 创建一个空文件
# 要注意重复>时,原来的文件会被清空。

>> 追加

tsc@tsc:~$ ls -l /usr/bin >> ls-output2.txt
#文件不存在会新建。

error 输出

tsc@tsc:~$ ls -l /bin/usr 2> ls-error.txt
# 我的问题:在不知道有没有error的情况下,>和2>要如何同时执行?

都输出到一个文件(有两种方法)

# 1.老版本
# 顺序很重要
ls -l /bin/usr > ls-output.txt 2>&
# 2.新,用&>
ls -l /bin/usr &> ls-output.txt
ls -l /bin/usr &>> ls-output.txt # 追加

Pipelines

ls -l /usr/bin | less
#千万不要把>用成|,不然有些后果很严重。

filters

tsc@tsc:~$ ls /bin /usr/bin | sort | less

7 符号变量

这节讲expansion, 就是*、~之类的,本质就是变量。

  1. echo – Display a line of text

    It prints out its text arguments on standard output

    tsc@tsc:~$ echo this is a test
    this is a test
    
    # Tilde Expansion
    tsc@tsc:~/playground$ echo ~
    /home/tsc
    
    #Arithmetic Expansion
    #形式:$((expression))
    tsc@tsc:~/playground$ echo $((2+2))
    4
    

brace expansion

括号中间不能有空格。

用途:批量创建有顺序的文件。

Parameter Expansion

Command Substitution

command的结果也可以作为expansion

echo $(ls)

双引号:Double Quotes

“$”, “\” (backslash), and “`” (backquote) 失效,但是parameter expansion, arithmetic expansion, and command substitution 仍有效。

注意区别:

echo $(cal)
echo "$(cal)"
# 空格、tab、换行符都被用来分割,双引号则抑制。所以前一个命令不会换行,后一个会。

单引号:Single Quotes

抑制所有expansions

escape character

和双引号一起使用,抑制部分符号

8 高级键盘技巧

这节讲键盘技巧,提高效率。主要是command line和history的技巧。command line的:移动,删除。history的上下一个命令。

  1. clear – Clear the screen
  2. history – Display the contents of the history list

9 权限

思考:多用户为什么存在?想想计算中心。

多用户存在要解决的问题:

  1. 一个用户的错误操作不能使计算机crash
  2. 一个用户不能影响其他用户

几个相关文件夹

/etc/passwd
User accounts .
/etc/group
groups
/etc/shadow
user's password

rwx Owner Group World

  1. id – Display user identity

    id
    uid=1000(tsc) gid=1000(tsc) groups=1000(tsc),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
    # root
    # id
    uid=0(root) gid=0(root) groups=0(root)
    
  2. chmod – Change File Mode

    chmod 600 foo.txt
    
  3. umask – Set Default Permissions

  4. su – Run A Shell With Substitute User And Group IDs

    默认是superuser

    su -
    exit
    
  5. sudo – Execute A Command As Another User

    纠正自己的认识,su,sudo是改变用户的,不一定是super,默认才是。

  6. chown – Change File Owner And Group

  7. chgrp – Change Group Ownership

  8. passwd - change user password

10 进程

Processes are how Linux organizes the different programs waiting for their turn at the CPU.

  1. ps - report a snapshot of the current processes.

  2. top - display Linux processes

  3. & - Putting A Process In The Background

  4. jobs - list the jobs that have been launched from our terminal.

  5. fg - Returning A Process To The Foreground

    为什么要回到前台来?后台的程序不受terminal的控制。

    Ctrl-z - Stopping (Pausing) A Process,注意和ctrl-c的区别,c是结束。

  6. bg - resume the program’s execution in the background

  7. kill - “kill” processes

  8. killall - kill processes by name

  9. halt

  10. poweroff

  11. reboot

  12. shutdown

Part two – 配置与环境变量

11 环境

什么是environment?

configuration的作用:store program settings

  1. printenv - print all or part of environment

    # 所有environment
    tsc@tsc:~$ printenv | less
    # 某一个environment
    tsc@tsc:~$ printenv USER
    tsc@tsc:~$ echo $HOME
    
  2. printenv 显示的一些常见变量:

    SHELL
    PATH   # 所有的,最新的
    
  3. set #will show both the shell and environment variables

    printenv和set的区别:printenv只显示environment variables,set显示shell和environment variables.

    追加

    PATH=$PATH:$HOME/bin
    
  4. export # tells the shell to make the contents of PATH available to child processes of this shell.

Login Shell Sessions :

/etc/profile     # global
~/.bash_profile
~/.bash_login    # 如果上面那个不存在,读这个
~/.profile       # 如果上面那个不存在,读这个
# .profile文件中有PATH,并且将$HOME/bin添加上了,所以启动系统后$HOME/bin中的命令是直接可以用的。$HOME是用户目录。

Non-Login Shell Sessions :

/etc/bash.bashrc # global
~/.bashrc        # user's

Text Editors

有两种:

1.graphical :gedit

2.text based :nano, vi, emacs

nano

ctrl-x : exit
ctrl-o : save, write out
#      : comments

使.bashrc生效

首先要知道原理,启动流程,在session一开始才会read .bashrc,所以需要重启terminal才会生效。当然,可以强行重读.bashrc,用source命令:

source .bashrc

12 vi 简介

  1. vi 操作

    :q
    :q!   *# 强制退出
    i     *# insert
    esc   *# to command mode
    :w    *# save ,有:的命令叫ex command
    
    # move
    h, j, k, l
    ctrl-f/b
    numberG
    gg # 第一个字符
    G last line of the file
    0 (zero) 行首
    ^ To the first non-whitespace character on the current line.
    $ end of current line
    w beginning of next word or punctuation
    W ignoring punctuation
    b beginning of previous word or punctuation
    B ignoring punctuation
    
    # edit
    u    # undo last change
    i    # insert
    
    # append
    a    # append, i是前插
    A    # 直接到最后append
    
    # opening a line
    o    # 新建一行在下面
    O    # 新建一行在上面
    
    # delete
    x    # current character
    3x
    dd   # current line,d有cut的作用
    dw   #
    dW   # ignoring punctuation
    d$   # current cursor to end
    d0   # current cursor to beginning
    dG   # current cursor to end of file
    d20G # current cursor to 20 line,不是要删除20行
    5dd  # 5行
    
    # Cutting, Copying, And Pasting
    p    # 小写粘贴在后一行(dd),普通在光标前
    P    # 大写粘贴在前一行(dd),普通在光标后
    p    # paste after cursor
    P    # upper case, paste before cursor
    
    # copy
    yy   # copy current line
    5yy  # copy 5 line
    yW   # ignoring punctuation
    yw   #
    y$   # current cursor to end of line
    y0   # current cursor to beginning of line
    y^   # current cursor to first non-whitespace char
    yG   # current cursor to last line of file
    y20G # current cursor to 20th line
    
    # redo,undo
    u  			# undo
    ctrl+r 	# redo
    J    		# join line
    
    # search, replace
    fa   		# 行内搜索a,按;继续搜索
    /    		# 文件内搜索,n继续
    :%s/line/Line/g    	# 替换
    :%s/line/Line/gc   	# 有提醒的替换,%代表对所有内容进行操作
    :1,2s/line/Line/gc 	# 对1-2行进行操作
    Ctrl-e, Ctrl-y 			# Scroll down and scroll up
    

The leading tilde characters (”~”) indicate that no text exists on that line.

modal editor

command mode

Switching case of characters 大小写转换

You can change the case of text:

Toggle case “HellO” to “hELLo” with g~ then a movement.

Uppercase “HellO” to “HELLO” with gU then a movement.

Lowercase “HellO” to “hello” with gu then a movement.

Alternatively, you can visually select text then press ~to toggle case, or U to convert to uppercase, or u to convert to lowercase.

常规操作

# 到行尾

$ 反:0

A 反:I

Word movement: w, e, b

13 自定义提示

- PS1-prompt string one

就是这个:

tsc@tsc:~$

更改它:

tsc@tsc:~$ PS1="<\u@\h \w>\$ "
<tsc@tsc ~>$ 
\u   # username of the current user.
\h   # Hostname of the local machine minus the trailing domain name.
\w   # Name of the current working directory.
\$   # This displays a “$” character unless we have superuser privileges. In that case, it displays a “#” instead.

改颜色:

通过escape code 实现,escape code 的开头是八进制的033 ,例子:

\033 [0;30m
# \033 是开头
# 0   是optional character attribute,0代表text color是normal,1是bold
# 30m 是instruction
tsc@tsc:~$ PS1="\[\033[0;31m\]<\u@\h \w>\$\[\033[0m\] "
\033[0m   *# 代表结束修改

Part three – 常见任务和基本工具

要知道package是什么,如何install, remove, update

14 – 包管理

linux的哪个发行版才是最好的?考虑的因素不是界面,而是:

  1. packaging system
  2. vitality of the distribution’s support community

packaging 的两大阵营:

  • Debian “.deb” camp
  • Red Hat “.rpm” camp
Packaging System     Distributions (Partial Listing)
Debian Style (.deb)  Debian, Ubuntu, Linux Mint, Raspbian
Red Hat Style (.rpm) Fedora, CentOS, Red Hat Enterprise Linux, OpenSUSE

- package files

- shared libraries

软件都是有依赖的,被依赖的就放在这里

dependency

- package tool

分为high, low-level两种,

high:metadata search, dependency

low-level: installing, removing

Red Hat系列使用同一low-lvel program(rpm), high-level则不同,yum使用者:Fedora, Red Hat Enter, CentOS.

Distributions Low-Level Tools High-Level Tools

Debian-Style dpkg apt-get, aptitude

Fedora, Red Hat, Enterprise Linux, CentOS rpm yum

查找和ackage的方法

- What is the difference between apt-get update and upgrade?

15 存储介质

什么是mounting?

attaching the device to the file system tree.

  1. mount – Mount a file system

没有参数时,显示已经mounted的文件系统。

如何看?device on mount_point type file_system_type (options).

free - Display amount of free and used memory in the system

partition number 是什么?

Unable to enumerate USB device under virtualbox

usb3.0插的3.0的口上在vm中读不出来,改插在2.0的口上就可以,真是。。。

磁盘、分区及Linux文件系统 [Disk, Partition, Linux File System]

inode的作用:实现文件存储的关键。

  1. tail的妙用
# ubuntu
tail -f /var/log/syslog

实时观察系统在做什么。

partition layout 是什么?

IDE、SATA、SCSI、SAS、FC、SSD硬盘类型介绍

  1. fsck - check and repair a Linux filesystem

16 网络

IP Addresses, Host Names, and Domain Names

明白host name与domain name的区别。

  1. ping, ping6 - send ICMP ECHO_REQUEST to network hosts
  2. traceroute - print the route packets trace to network host
  3. ip - show / manipulate routing, devices, policy routing and tunnels

DHCP (Dynamic Host Configuration Protocol)

  1. netstat - Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships
  2. ftp — Internet file transfer program

ftp是明文传输。

  1. Wget - The non-interactive network downloader.
  2. ssh

rlogin and telnet 和ftp有一样的缺陷。

ssh解决了两大问题:First, it authenticates that the remote host is who it says it is (thus preventing so-called “man in the

middle” attacks), and second, it encrypts all of the communications between the local and

remote hosts.

ssh root@ip -p 端口号

windows下的ssh软件:PuTTY

17 文件搜索

  1. locate - find files by name

    locate查找的数据库是如何更新的?由updatedb 程序更新,可以手动更新。

    locate vs find: usage, pros and cons of each other

  2. find - search for files in a directory hierarchy
    find 参数很多,本文只介绍几个常用的

    -name 按名字查找
    -type 按类型
    -atime 访问时间

    $ find ~ -type f | wc
    # 文件名有jpg,大小大于1M
    $ find ~ -type f -name "*.jpg" -size +1M | wc -l
    
    find . -atime 7 -type f -print
    find . -type d -print  //只列出所有目录
    find / -name "hello.c" 查找hello.c文件
     
    #test
    $ find ~ \( -type f -not -perm 0600 \) -or \( -type d -not -perm 0700 \)
    
    # 顺序很重要。
    # action:把查找的结果作为命令的输入参数
    
    $ find ~ -type f -name 'foo*' -exec ls -l '{}' ';'
    $ find ~ -type f -name 'foo*' -exec ls -l '{}' +
    $ find ~ -type f -name 'foo*' -print | xargs ls -l
    # {} is a symbolic representation of the current pathname
    # +:the system only has to execute the ls command once
    
    #文件名中空格的处理
    $ find ~ -type f -name '*.jpg' -print0 | xargs --null ls -l
    
  3. touch - change file timestamps

    文件不存在时会创建。

  4. stat - display file or file system status

    which is a kind of souped-up version of ls.

18 存档和备份

管理大量的文件-压缩。

本节讲3个内容:

compression(压缩)

archiving(归档)

synchronization(同步)

  1. gzip, gunzip, zcat - compress or expand files

    gzip压缩,gunzip解压。

    gzip会替换原来的文件。

  2. zcat - equivalent to gunzip with the -c option

  3. zless

  4. bzip2, bunzip2 - a block-sorting file compressor

  5. linux压缩和打包是两个要领,分别对应zip和tar,window下面是不是没有区分?

  6. tar -tape archive

    .tar or .tgz, which indicate a “plain” tar archive and a gzipped archive, respectively.

    # c create
    $ tar cf playground.tar playground
    
    # t list
    $ tar tf playground.tar
    
    # x extract
    $ tar xf ../playground.tar
    # r append
    
    # extract a single file
    $ tar xf archive.tar pathname
    

    注意区分mode与option,c是mode,f是option。mode要先写。

  7. incremental backups - 增量式备份

  8. linux shell 重定向 减号-的作用

    studout或者stdin就可以用减号(-)来替代

  9. 不解压缩直接查看.gz和.bz2命令

    使用zcat可以查看*.gz文件内容,使用bzcat可以直接查看*.bz2文件.

  10. 用ssh从远程服务器复制文件到本地

    ssh root@xxx.xxx.xx.xx -p 端口号 'tar cf - filename' | tar xf -
    root@xxx.xxx.xx.xx's password: 
    

    先tar,传回来再导出。

  11. zip - 既压缩也归档

  12. zip, unzip的作用是交换windows文件,linux用tar, gzip

  13. rsync - 备份与同步

    rsync options source destination
    $ rsync -av playground foo
    

19 – 正则表达式

后面几章都是关于文字处理的。先讲regular expression.

  1. metacharacters & literal characters

    metacharacters是^ $ . [ ] { } - ? * + ( ) | \ ,其余就是literal characters。

  2. The Any Character

    就是点号,the dot or period character

  3. anchors

    The caret (^) (只匹配行首出来的)and dollar sign ($) (只匹配行尾出现的)

    $ grep -h '^zip' dirlist*.txt
    $ grep -h 'zip$' dirlist*.txt
    $ grep -h '^zip$' dirlist*.txt
    
  4. 点号不是任意长度吗?加上^$就代表一个?

    $ grep -h '.zip' dirlist*.txt
    $ grep -i '^..j.r$' /usr/share/dict/words
    
  5. Bracket Expressions And Character Classes

    [] 用来只匹配一个字符。

    $ grep -h '[bg]zip' dirlist*.txt
    ^ : negation,只在第一个位置时有效
    $ grep -h '[^bg]zip' dirlist*.txt # 注意出现的位置,表示取反
    : rang$ grep -h '^[A-Za-z0-9]' dirlist*.txt
    # 要匹配-(短横线),就把它放到第一位
    $ grep -h '[A-Z]' dirlist*.txt
    $ grep -h '[-AZ]' dirlist*.txt
    
  6. POSIX Character Classes

    出现的原因:posix和ASCII不一样。

  7. alternation

    []是单个,它(|)是string

    $ echo "AAA" | grep -E 'AAA|BBB|CCC'
    $ grep -Eh '^(bz|gz|zip)' dirlist*.txt
    
  8. Quantifiers

    匹配的个数

    # ? - Match An Element Zero Or One Time ,一个字符出现的次数,和word里面的?不同,word里面代表任意一个字符,这里的?不能单独使用,要跟在一个字符后面。
    $ echo "(555) 123-4567" | grep -E '^\(?[0-9][0-9][0-9]\)? [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$'
    
    # * - Match An Element Zero Or More Times
    $ echo "This works." | grep -E '[[:upper:]][[:upper:][:lower:] ]*\.'
    # 和?一样,前面要有字符。
    
    # + - Match An Element One Or More Times 至少出现一次。
    $ echo "This that" | grep -E '^([[:alpha:]]+ ?)+$'
    
    # { } - Match An Element A Specific Number Of Times
    $ echo "(555) 123-4567" | grep -E '^\(?[0-9]{3}\)? [0-9]{3}-[0-9]{4}$'
    
  9. find使用reg

    $ find . -regex '.*[^-_./0-9a-zA-Z].*'
    # 反 0-无穷个字符
    
  10. locate使用reg

    $ locate --regex 'bin/(bz|gz|zip)'
    
  11. less和vi中也可以使用(注意它们的区别,在vi中reg是basic)

    # less
    /^\([0-9]{3}\) [0-9]{3}-[0-9]{4}
    
    # vi
    /([0-9]\{3\}) [0-9]\{3\}-[0-9]\{4\}
    

20 文本处理

真是一切皆文件。

  1. cat的一些option

    $ cat -A foo.txt # 显示所有符号,包括控制符
    $ cat -ns foo.txt # n显示行号,s抑制多余的空行
    
  2. sort

    -n 按数字进行排序 VS -d 按字典序进行排序
    -r 逆序排序
    -k N 指定按第N列排序

    sort -nrk 1 data.txt
    sort -bd data // 忽略像空格之类的前导空白字符
     
    $ sort > foo.txt
    c
    b
    a
    
    # 多个文件
    $ sort file1.txt file2.txt file3.txt > final_sorted_list.txt
       
    #按指定列排序(k):
    $ ls -l /usr/bin | sort -nr -k 5 | head
    
    #多个key排序:
    $ sort --key=1,1 --key=2n distros.txt
    
    # 一个field内多个排序:
    $ sort -k 3.7nbr -k 3.1nbr -k 3.4nbr distros.txt
    
    #指定分割符:
    $ sort -t ':' -k 7 /etc/passwd | head
    
  3. du - estimate file space usage

    $ du -s /usr/share/* | head # 显示前10个
    $ du -s /usr/share/* | sort -nr | head # 大到小排序后显示前10个
    
  4. uniq 去重

    $ sort foo.txt | uniq
    
  5. wc 统计

    wc -l file // 统计行数
    wc -w file // 统计单词数
    wc -c file // 统计字符数
    
  6. cut

    # 取第3列
    $ cut -f 3 distros.txt
    
    #每个field的长度可能不同,如果要取所有行中时间中的年,就不可能用字符位置去表示。而先把field取出来,就规整了。
    $ cut -f 3 distros.txt | cut -c 7-10
    
  7. expand - 把tab换为等量空格

    $ expand distros.txt | cut -c 23-
    
  8. 改cut的默认分割符,用d option

    $ cut -d ':' -f 1 /etc/passwd | head
    
  9. paste

    adds one or more columns of text to a file

    $ sort -k 3.7nbr -k 3.1nbr -k 3.4nbr distros.txt > distros-by-date.txt
    $ cut -f 1,2 distros-by-date.txt > distros-versions.txt
    $ cut -f 3 distros-by-date.txt > distros-dates.txt
    $ paste distros-dates.txt distros-versions.txt
    
  10. join
    It joins data from multiple files based on a shared key field.

    $ join distros-key-names.txt distros-key-vernums.txt | head
    
  11. comm

    $ comm file1.txt file2.txt
    # -n 抑制列
    $ comm -12 file1.txt file2.txt
    
  12. diff

    $ diff file1.txt file2.txt
    
    # context format 看两个各自都有什么,没有什么
    $ diff -c file1.txt file2.txt
    
    # unified format 看从旧到新的变化
    $ diff -u file1.txt file2.txt
    
  13. patch 用来更新文件,比如代码。

    apply changes to text files。

    $ diff -Naur file1.txt file2.txt > patchfile.txt
    
    $ patch < patchfile.txt
    
  14. tr 转换

    $ echo "lowercase letters" | tr a-z A-Z
    LOWERCASE LETTERS
    # 多对一的转换
    $ echo "lowercase letters" | tr [:lower:] A
    # squeeze
    $ echo "aaabbbccc" | tr -s ab
    abccc
    
  15. grep
    grep match_patten file // 默认访问匹配行
    常用参数

    -o 只输出匹配的文本行 VS -v 只输出没有匹配的文本行
    -c 统计文件中包含文本的次数 grep -c “text” filename
    -n 打印匹配的行号
    -i 搜索时忽略大小写
    -l 只打印文件名

    # 在多级目录中对文本递归搜索(程序员搜代码的最爱)
    grep "class" . -R -n 
    
    #将日志中的所有带where条件的sql查找查找出来
    cat LOG.* | tr a-z A-Z | grep "FROM " | grep "WHERE" > b 
    
  16. sed:stream editor
    用法:sed [options] ‘command’ file(s)

    # search-and-replace
    $ echo "aaabbbccc" | sed 's/b/B/'	#首处替换
    $ echo "aaabbbccc" | sed 's/b/B/g'	#全部替换
    
    # 谁跟在command后面就是delimiter
    $ echo "front" | sed 's_front_back_'
    
    # 指定要处理的行数
    $ echo "front" | sed '1s/front/back/'
    
    # p:打印出来
    # -n:  not to print every line by default
    
    $ sed -n '1,5p' distros.txt
    $ sed -n '/SUSE/p' distros.txt
    $ sed -n '/SUSE/!p' distros.txt
    
    # 一般出输出到屏幕,用i则直接替换原文件
    $ sed -i 's/lazy/laxy/; s/jumped/jimped/' foo.txt
    
    #删除空白行
    sed '/^$/d' file 
    
    #reg的back references
    $ sed 's/\([0-9]\{2\}\)\/\([0-9]\{2\}\)\/\([0-9]\{4\}\)$/\3-\1-\2/' distros.txt
    
  17. awk
    详细教程可以查看 http://awk.readthedocs.io/en/latest/chapter-one.html

    awk ’ BEGIN{ statements } statements2 END{ statements } ’
    工作流程:

    1.执行begin中语句块;
    2.从文件或stdin中读入一行,然后执行statements2,重复这个过程,直到文件全部被读取完毕;
    3.执行end语句块;

    特殊变量:

    NR:表示记录数量,在执行过程中对应当前行号;
    NF:表示字段数量,在执行过程总对应当前行的字段数;
    $0:这个变量包含执行过程中当前行的文本内容;
    $1:第一个字段的文本内容;
    $2:第二个字段的文本内容;

    awk '{print $2, $3}' file
    # 日志格式:'$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"'
    
    #统计日志中访问最多的10个IP
    awk '{a[$1]++}END{for(i in a)print a[i],i|"sort -k1 -nr|head -n10"}' access.log
    
  18. aspell 拼写检查

    $ aspell check foo.txt
    
    # -H (HTML) checking-mode option
    $ aspell -H check foo.txt
    

    改完了会产生一个bak文件,存在原来的文本。

21 格式化输出

讲文本输出格式。

  1. nl 显示行号

    $ nl distros.txt | head
    
    # 和cat -n 一样
    $ sort -k 1,1 -k 2n distros.txt | sed -f distros-nl.sed | nl
    
  2. fold – Wrap Each Line To A Specified Length

    $ echo "The quick brown fox jumped over the lazy dog." | fold -w 12
    
    # 不打断单词
    $ echo "The quick brown fox jumped over the lazy dog." | fold -w 12 -s
    
  3. fmt – A Simple Text Formatter

    it fills and joins lines in text while preserving blank lines and indentation.

    $ fmt -w 50 fmt-info.txt | head
    $ fmt -cw 50 fmt-info.txt
    # 一行如果不足50个字符,会把第二行的补过来
    # 只对'# '开头的行操作
    $ fmt -w 50 -p '# ' fmt-code.txt
    
  4. pr – Format Text For Printing

    used to paginate text.

    # l:page length
    # w:width
    $ pr -l 15 -w 65 distros.txt
    
    #首尾会有空行。
    
  5. printf – Format And Print Data

    #使用:printf “format” arguments
    $ printf "I formatted the string: %s\n" foo
    $ printf "%d, %f, %o, %s, %x, %X\n" 380 380 380 380 380 380
    
    #Multiple optional components :
    %[flags][width][.precision]conversion_specification
    
  6. Document Formatting Systems

    tex后来取代了troff.

  7. groff

    $ zcat /usr/share/man/man1/ls.1.gz | head
    $ man ls | head
    $ zcat /usr/share/man/man1/ls.1.gz | groff -mandoc -T ascii | head
    
    # 存为postscript到桌面
    $ zcat /usr/share/man/man1/ls.1.gz | groff -mandoc > ~/Desktop/foo.ps
    
    # ps转pdf
    $ ps2pdf ~/Desktop/foo.ps ~/Desktop/ls.pdf
    
  8. tbl

22 打印

介绍了ps的由来。

1. CUPS (Common Unix Printing System) :provides print drivers and print-job management

2. Ghostscript: a PostScript interpreter, acts as a RIP.

  1. pr – Convert Text Files For Printing

    pr is used to adjust text to fit on a specific page size, with optional page headers and margins.

    # 3列
    $ ls /usr/bin | pr -3 -w 65 | head
    

3. CUPS 有两种printing,lpr, lp.

  1. lpr – Print Files (Berkeley Style)

    $ ls /usr/bin | pr -3 | lpr
    
  2. lpr: Error - no default destination available.

    # 查看printer
    $ lpstat -a
    lpstat: No destinations added.
    
  3. lp – Print Files (System V Style)

  4. a2ps

    “Anything to PostScript.”
    $ ls /usr/bin | pr -3 -t | a2ps -o ~/Desktop/ls.ps -L 66 -R
    
  5. lpstat – Display Print System Status

    # 查询printer状态
    $ lpstat -a
    $ lpstat -a
    
  6. lpq – Display Printer Queue Status

    $ lpq
    PDF is ready
    no entries
    
  7. lprm / cancel – Cancel Print Jobs

23 程序编译

  1. compile

    linker,解决共享问题,用共享库。

    $ which gcc
    /usr/bin/gcc
    
  2. 用ftp下载source code

    $ mkdir src
    $ cd src
    
    $ ftp ftp.gnu.org
    Name (ftp.gnu.org:me): anonymous
    ftp> cd gnu/diction
    ftp> ls
    ftp> get diction-1.11.tar.gz
    ftp> bye
    $ tar xzf diction-1.11.tar.gz
    
    # 先查看是不是在一个文件夹里,以免解压散开
    $ tar tzvf diction-1.11.tar.gz | less
    

    共享的头文件在/usr/include ,The header files in this directory were installed when we installed the compiler.

  3. Building The Program

    一般需要两步。

    # 由于script不在默认的目录,需要./告诉shell它在当前目录
    $ ./configure
    
    config.status: creating Makefile
    config.status: creating diction.1
    config.status: creating diction.texi
    config.status: creating diction.spec
    config.status: creating style.1
    config.status: creating test/rundiction
    config.status: creating config.h
    
    # Makefile is a configuration file that instructs the make program exactly how to build the program. Without it, make will refuse to run.
    #make只complie需要complie的文件,省时间。
    $ make	&& make install
    #Installing The Program
    
    
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值