perl中heredoc使用验证,Shell编制程序技艺

格式

这是自家写BASH程序的招式。这里本没有什么样新的开始和结果,不过从自己的经历来看,大家爱滥用BASH。他们忽略了Computer科学,而从他们的主次中创建的是“大泥球”(译注:指架构不清楚的软件系统)。

Linux的一声令下总计

一、列出当天访谈次数最多的IP 命令:

print <<EOF
you text go here
EOF

在此小编告诉你方法,以保险你的主次免于障碍,并保险代码的卫生。

1、 man:在线乞求系统帮忙

复制代码 代码如下:

复制代码 代码如下:

一、不可更换的全局变量

例:man mkdir

cut -d- -f 1 /usr/local/apache2/logs/access_log |uniq -c | sort -rn |
head -20

sub usage{
    print <<EOF;
Usage: test.pl -c config, -f file -l lines
    -c config file
    -f file name
    -l number of lines
EOF
}

1.尽量少用全局变量
2.以大写命名
3.只读阐明
4.用全局变量来代表隐晦的$0,$1等

 

原理:

NOTE: the last EOF must start at the beginning of the line!!!
you can use other words instead of EOF

在我的主次中常使用的全局变量:

 美高梅开户网址 1

复制代码 代码如下:

复制代码 代码如下:

 

       cut
       -d, –delimiter=DELIM
              use DELIM instead of TAB for field delimiter
              表示用-分割,然后-f 1
       -f, –fields=LIST
              select only these fields;  also print any line that
contains  no
              delimiter character, unless the -s option is specified
           表示打字与印刷第一片段,便是ip
 uniq 是将重新行去掉, -c表示前边后面加上数量,
       sort -rn 便是鲁人持竿数字从大到小排序,
       head -20取前面20行

readonly PROGNAME=$(basename $0)
readonly PROGDIR=$(readlink -m $(dirname $0))
readonly ARGS=”$@”

 美高梅开户网址 2

      
终极打字与印刷的结果大概是那般:

二、一切皆是一些的

 

复制代码 代码如下:

持有变量都应该为局地的。

NAME:这么些命令的一体化全名 mk(make directories)

   217 192.114.71.13
   116 124.90.132.65
   108 192.114.71.13
   102 194.19.140.96
   101 217.70.34.173
   100 219.235.240.36

复制代码 代码如下:

SYNOPSIS:那个命令的中坚语法

以下是任何部分解析日志的shell用法:

change_owner_of_file() {
    local filename=$1
    local user=$2
    local group=$3

    mkdir [OPTION]… DIRECTORY…

1、查看当天有微微个IP访谈:

    chown $user:$group $filename
}
change_owner_of_files() {
    local user=$1; shift
    local group=$1; shift
    local files=$@
    local i

        OPTION:参数

复制代码 代码如下:

    for i in $files
    do
        chown $user:$group $i
    done
}

        DERECTORubiconY:目录只怕表现

awk ‘{print $1}’ log_file|sort|uniq|wc -l

1.自注释(self documenting)的参数
2.普通作为循环用的变量i,把它评释为局地变量是比较重要的。
3.局地变量不效用于全局域。

DESC驭胜IPTION:具体描述命令的利用办法

2、查看某一个页面被访谈的次数;

复制代码 代码如下:

   

复制代码 代码如下:

kfir@goofy ~ $ local a
bash: local: can only be used in a function

    -m, –mode=MODE

grep “/index.php” log_file | wc -l

三、main()

              set file mode (as in chmod), not a=rwx – umask

3、查看每贰个IP访谈了略微个页面:

1.推进维持全数变量的区域性
2.直观的函数式编制程序
3.代码中无可比拟的大局命令是:main

        左侧的-m为短参数,右侧的–mode为完全参数名称

复制代码 代码如下:

复制代码 代码如下:

       
设置目录的状态(这里能够知晓为权力),和chmod那个命令一样,并非默许权限

awk ‘{++S[$1]} END {for (a in S) print a,S[a]}’ log_file

main() {
    local files=”/tmp/a /tmp/b”
    local i

用法:

4、将种种IP访谈的页面数举办从小到大排序:

    for i in $files
    do
        change_owner_of_file kfir users $i
    done
}
main

        mkdir 777 test.c 使用短参数

复制代码 代码如下:

四、一切皆是函数

        等价于

awk ‘{++S[$1]} END {for (a in S) print S[a],a}’ log_file | sort -n

独一全局性运营的代码是:

        mkdir –mode 777 test1 使用长参数

5、查看某一个IP访问了什么页面:

  • 不可变的全局变量证明
  • main()函数

AUTHOR:作者

复制代码 代码如下:

1.保证代码整洁
2.进度变得明明白白

 

grep ^111.111.111.111 log_file| awk ‘{print $1,$7}’

复制代码 代码如下:

REPORTING BUGS:如若出现难点,请发邮件或然登陆表明的网站

6、去掉搜索引擎计算当天的页面:

main() {
    local files=$(ls /tmp | grep pid | grep -v daemon)
}

 

复制代码 代码如下:

复制代码 代码如下:

COPY福特ExplorerIGHT:受到了文章权的法律尊敬,是GPL

awk ‘{print $12,$1}’ log_file | grep ^\”Mozilla | awk ‘{print $2}’
|sort | uniq | wc -l

temporary_files() {
    local dir=$1

 

7、查看2010年二月29日14时那三个钟头内有多少IP访问:

    ls $dir \
        | grep pid \
        | grep -v daemon
}

SEE ALSO:还能在何地查询这一个命令的选择方式,比如:info mkdir

复制代码 代码如下:

main() {
    local files=$(temporary_files /tmp)
}

 

awk ‘{print $4,$1}’ log_file | grep 21/Jun/2009:14 | awk ‘{print $2}’|
sort | uniq | wc -l

1.次之个例证好得多。查找文件是temporary_files()的主题材料而非main()的。这段代码用temporary_files()的单元测量试验也是可测验的。

按键:

您也许感兴趣的文章:

  • linux
    shell命令飞快获得系统辅助(一)[man-pages定义标准]
  • linux
    shell命令行选项与参数用法详解
  • linux
    shell脚本学习xargs命令使用详解
  • linux中 shell
    历史命令记录作用
  • Linux命令行和shell脚本编制程序宝典 RichardBlum
  • linux
    shell命令实践顺序的支配方法
  • Ruby中实行Linux
    shell命令的二种办法详解
  • linux
    shell命令行参数用法详解
  • Linux
    Shell脚本体系教程(二):终端打印命令详解
  • Linux
    shell命令补助格式详解

2.假若你应当要尝尝第五个例证,你会博得查找不时文件以和main算法的大杂烩。

    [Page Dowm]: 向下翻页

复制代码 代码如下:

    [空格键]: 向下翻页

test_temporary_files() {
    local dir=/tmp

    [page Up]:向上翻页

    touch $dir/a-pid1232.tmp
    touch $dir/a-pid1232-daemon.tmp

    [Home]:回到首页

    returns “$dir/a-pid1232.tmp” temporary_files $dir

    [End]:回到末页

    touch $dir/b-pid1534.tmp

    /String:向下询问字符串,假使要向下询问vbird,使用输入/vbird

    returns “$dir/a-pid1232.tmp $dir/b-pid1534.tmp” temporary_files
$dir
}

    ?String:向上查询字符串,

如您所见,这几个测量检验不关心main()。

   
n/N:利用/也许?来询问字符串时,能够利用n来继续下二个查询(不论是\抑或?),能够动用N来向下询问。比释迦牟尼说,笔者以/vbird查询vbird字符串,那么笔者得以采纳n来往下询问,使用N来

五、调节和测验函数

    q:截至此次的man page

带-x标识运营程序:

 

复制代码 代码如下:

touch

bash -x my_prog.sh

 

只调节和测量检验一小段代码,使用set-x和set+x,会只对被set -x和set
+x包罗的当前代码打字与印刷调节和测量检验音讯。

touch:chage file timestamps

复制代码 代码如下:

       update the access and modification times of each FILE to current
time .

temporary_files() {
    local dir=$1

        A FILE argument that does not exsit is created empty unless -c
or -h is suppiled

    set -x
    ls $dir \
        | grep pid \
        | grep -v daemon
    set +x
}

    参数:

打字与印刷函数名和它的参数:

        -a:change only the access time

复制代码 代码如下:

        -c:do not create any files

temporary_files() {
    echo $FUNCNAME $@
    local dir=$1

        -d –date=STRING:parse STRING and use it instead of use current
time

    ls $dir \
        | grep pid \
        | grep -v daemon
}

        -f:ignore

调用函数:

        -m:change only the modification time

复制代码 代码如下:

        -t STAMP:use [YYMMDDhhmm] instead of current time

temporary_files /tmp

        –time=WORD:change specified time :WORD is access,atime,or
use:equivalent to -a WORD is modify or mtime:equivalent to -m

会打字与印刷到专门的学问输出:

 

复制代码 代码如下:

atime:access time :file is executed or read

temporary_files /tmp

ctime:creat time :file is change including content,owner,authority and
so on

六、代码的清晰度

mtime:modify time:file is written

这段代码做了怎么样?

 

复制代码 代码如下:

so if a file is written all time will change

main() {
    local dir=/tmp

 

    [[ -z $dir ]] \
        && do_something…

If you want know more ,please click:

    [[ -n $dir ]] \
        && do_something…

    [[ -f $dir ]] \
        && do_something…

 

    [[ -d $dir ]] \
        && do_something…
}
main

 

令你的代码说话:

LS

复制代码 代码如下:

 

is_empty() {
    local var=$1

ls – list directory contents

    [[ -z $var ]]
}

    List information about the FILES (the curren directory by
default),sort entries alphabetically if none of -cftuzSUX nor

is_not_empty() {
    local var=$1

 -–sort

perl中heredoc使用验证,Shell编制程序技艺。    [[ -n $var ]]
}

    -a,–all list

is_file() {
    local file=$1

do not ignore entries starting with .

    [[ -f $file ]]
}

    -A –almost-all

is_dir() {
    local dir=$1

           Do not list imply . and ..

    [[ -d $dir ]]
}

    –author

main() {
    local dir=/tmp

           With l print the author of each file

    is_empty $dir \
        && do_something…

    -d –-directory

    is_not_empty $dir \
        && do_something…

           list directory entries instead of conents,and do not
dereference  symblolic links

    is_file $dir \
        && do_something…

    -f

    is_dir $dir \
        && do_something…
}
main

        Do not sort,enable -aU

七、每一行只做一件事

    -F –- classify

用反斜杠\来作分隔符。比方:

        append indicator (one of */=>@|) to entries

复制代码 代码如下:

    -h –human-readable

temporary_files() {
    local dir=$1

        With -l,print sizes human readable format(e.g.,234M,2G)

    ls $dir | grep pid | grep -v daemon
}

    -l

能够写得简洁得多:

        Use long list format

复制代码 代码如下:

    -S

temporary_files() {
    local dir=$1

        sort by file size

    ls $dir \
        | grep pid \
        | grep -v daemon
}

    -t

标记在缩实行的早先

        sort by modification time

标识在行末的坏例子:(译注:原来的书文在此例中用了temporary_files()代码段,疑似是贴错了。结合上下文,应该为print_dir_if_not_empty())

    -i

复制代码 代码如下:

        print the index number of each file

print_dir_if_not_empty() {
    local dir=$1
 
    is_empty $dir && \
        echo “dir is empty” || \
        echo “dir=$dir”
}

 

好的事例:大家能够清晰看到行和连接符号之间的联络。

           for example, use i l and h .             

复制代码 代码如下:

 美高梅开户网址 3

print_dir_if_not_empty() {
    local dir=$1

 

    is_empty $dir \
        && echo “dir is empty” \
        || echo “dir=$dir”
}

-F –classify

八、打字与印刷用法

    append indicator(one of */=>@|) to entries

毫不这么做:

   美高梅开户网址 4

复制代码 代码如下:

 

echo “this prog does:…”
echo “flags:”
echo “-h print help”

usually use -F will add / at the end of the directory, so you can use it
and grep to easily get directories.

它应当是个函数:

for example:

复制代码 代码如下:

 美高梅开户网址 5

usage() {
    echo “this prog does:…”
    echo “flags:”
    echo “-h print help”
}

 

echo在每一行再一次。因而大家赢得了那么些文档:

    -p –indicator–style=slash

复制代码 代码如下:

        append / indicator to directories

usage() {
    cat <<- EOF
    usage: $PROGNAME options
   
    Program deletes files from filesystems to release space.
    It gets config file that define fileystem paths to work on, and
whitelist rules to
    keep certain files.

    we also think it: -F contain -p

    OPTIONS:
       -c –config              configuration file containing the rules.
use –help-config to see the syntax.
       -n –pretend             do not really delete, just how what you
are going to do.
       -t –test                run unit test to check the program
       -v –verbose             Verbose. You can specify more then one
-v to have more verbose
       -x –debug               debug
       -h –help                show this help
          –help-config         configuration help

    -r –reverse

   
    Examples:
       Run all tests:
       $PROGNAME –test all

        reverse order while sorting

       Run specific test:
       $PROGNAME –test test_string.sh

    if you want find the latest file you create of many files,you can
use: ls -lrt

       Run:
       $PROGNAME –config /path/to/config/$PROGNAME.conf

 美高梅开户网址 6

       Just show what you are going to do:
       $PROGNAME -vn -c /path/to/config/$PROGNAME.conf
    EOF
}

 

瞩目在每一行的行首应该有一个当真的制表符‘\t’。

 

在vim里,纵然您的tab是4个空格,你可以用那一个替换命令:

 

复制代码 代码如下:

 

:s/^    /\t/

mkdir

九、命令行参数

mkdir — make directory

这里是一个事例,实现了上边usage函数的用法。作者从
获得这段代码

    Create the DIRECTOTY(ies) if the they do not already exsit

复制代码 代码如下:

    args:

cmdline() {
    # got this idea from here:
    #

    local arg=
    for arg
    do
        local delim=””
        case “$arg” in
            #translate –gnu-long-options to -g (short options)
            –config)         args=”${args}-c “;;
            –pretend)        args=”${args}-n “;;
            –test)           args=”${args}-t “;;
            –help-config)    usage_config && exit 0;;
            –help)           args=”${args}-h “;;
            –verbose)        args=”${args}-v “;;
            –debug)          args=”${args}-x “;;
            #pass through anything else
            *) [[ “${arg:0:1}” == “-” ]] || delim=”\””
                args=”${args}${delim}${arg}${delim} “;;
        esac
    done

        -m,–mode=MODE

    #Reset the positional parameters to the short options
    eval set — $args

           set file mode (as in chomd),not a=rwx -umask

    while getopts “nvhxt:c:” OPTION
    do
         case $OPTION in
         v)
             readonly VERBOSE=1
             ;;
         h)
             usage
             exit 0
             ;;
         x)
             readonly DEBUG=’-x’
             set -x
             ;;
         t)
             RUN_TESTS=$OPTARG
             verbose VINFO “Running tests”
             ;;
         c)
             readonly CONFIG_FILE=$OPTARG
             ;;
         n)
             readonly PRETEND=1
             ;;
        esac
    done

                      umask:default authority

    if [[ $recursive_testing || -z $RUN_TESTS ]]; then
        [[ ! -f $CONFIG_FILE ]] \
            && eexit “You must provide –config file”
    fi
    return 0
}

        -p –parents

您像这么,使用我们在头上定义的不可变的A昂CoraGS变量:

           no error if existing ,make parent directories as needed

复制代码 代码如下:

 

main() {
    cmdline $ARGS
}
main

       -v –verbose

十、单元测量检验

           -v, –verbose

1.在越来越尖端的言语中很入眼。
2.行使shunit2做单元测量检验

              print a message for each created directory

复制代码 代码如下:

 

test_config_line_paths() {
    local s=’partition cpm-all, 80-90,’

     -Z, –context=CTX

    returns “/a” “config_line_paths ‘$s /a, ‘”
    returns “/a /b/c” “config_line_paths ‘$s /a:/b/c, ‘”
    returns “/a /b /c” “config_line_paths ‘$s   /a  :    /b : /c, ‘”
}

         set the SELinux security context of each created directory to
CTX

config_line_paths() {
    local partition_line=”$@”

 

    echo $partition_line \
        | csv_column 3 \
        | delete_spaces \
        | column 1 \
        | colons_to_spaces
}

 

source /usr/bin/shunit2

cp(copy)

此处是另三个应用df命令的例证:

 

复制代码 代码如下:

copy — copy files and directories

DF=df

    args

mock_df_with_eols() {
    cat <<- EOF
    Filesystem           1K-blocks      Used Available Use% Mounted on
    /very/long/device/path
                         124628916  23063572 100299192  19% /
    EOF
}

       -a –archive

test_disk_size() {
    returns 1000 “disk_size /dev/sda1”

           same as -dR –preserve=all

    DF=mock_df_with_eols
    returns 124628916 “disk_size /very/long/device/path”
}

          

df_column() {
    local disk_device=$1
    local column=$2

       -d:若为连接文件,则复制文件本人

    $DF $disk_device \
        | grep -v ‘Use%’ \
        | tr ‘\n’ ‘ ‘ \
        | awk “{print \$$column}”
}

       -i –interactive

disk_size() {
    local disk_device=$1

           prompt before overwrite(overrides a previous -n position)  

    df_column $disk_device 2
}

       -p

此地我有个不相同,为了测量试验,笔者在全局域中扬言了DF为非只读。那是因为shunit2差别意改换全局域函数。

           same as -preserve=mode,ownership,timestamps,using 备份

您可能感兴趣的稿子:

  • bash
    shell命令行选项与修传入参数管理
  • Bash Shell
    注释多行的二种方法
  • 动用bash
    shell删除目录中的特定文件的3种格局
  • linux BASH
    shell下设置字体及背景颜色
  • Bash Shell字符串操作小结
  • csh,tcsh,bash,sh等shell的区别
  • Bash Shell中Shift用法分享
  • Shell
    编制程序:Bash空格的这点事
  • Bash
    Shell中忽略大小写的装置格局
  • shell(bash)下“time”
    命令的出口详解

 

-r –recursive

    copy directories recursively

 

   

      

   

 

rm

rm –remove directories or files

    args:

       -f –force

           ignore nonexistent files,never prompt

       -i

           prompt before every removal

       -r –recursive

           remove directories and their contents recursiveable

 

 

mv

mv –move(rename) files

    args:

       -f –force

           do not prompt before overwriting

       -i –interactive

           prompt before overwriting

       -u –update

           move only when the SOURCE is newer than destination file or
destination file is missing

 

 

echo

 

echo –display a line of a text

    -n do not output the trailing newline

    for example:

   美高梅开户网址 7

 

    -e enable interpretation of backslash escapes

       If e in effect the following sequences are recognized

           \n new line

           \t vertical tab

           for example:

          美高梅开户网址 8

 

      

    Example:

       create a file and write a line content:

 echo “This is a test file” > test.file

           if you execute the command secondly,it will overwrite the
file and if you want to add  not to overwrite,you could use the command:

echo “This is a test file” >> test.file

1、 if PATH is a variable param is system,you use echo $PATH to input
its value

2、 echo 123 –> 123

 

 

 

cat&tac

    cat — concatenate files and print on the standard output

       -a –show-all

           equivalent to -vET

       -b –number-noneblank

           number nonempty output lines

       -e

           equvilent to -vE

       -E –show-ends

           display $ at the end of each line

       -n –number

           number all output lines

       -T –show-tabs

           display TAB characters as ^I

       -v show-nonprinting

           use ^ and M- natation except for LFD and TAB

 

       Example:

       if you want use cat to create file,you can use follow

       cat > test.file <<EOF

> ds

> dssdwew

> weew

> EOF

 

the content between EOE will be writtern the file and if the file is not
exsit,will create or overwrite

 

tac: concatenate and print files in inverse

 美高梅开户网址 9

 

 

 

pwd

pwd –print name of current/working directory

        Print full name of current working directory

    -L –logcial

           use PWD from envirment,even if contains symlinks

    -P –physical

           avoid all symlinks

 

 

 

alias

alias –set a name or var of a long command or character

    Example:

       1、alias:show all alias in you system or user

 美高梅开户网址 10

 

    “cp = ‘cp -i’” mean that if you cp a file to destination directory
and exsiting a same name file in the directory,The system will ask you
whether overwrite

2、 if want to set some alias,you can do follow:

alias cat=’cat -n’,use cat to represent cat -n

in ‘ ’ ,you should use command

 

3、 if wan cancel some alias,you can use follow:

  unalias cat

But we suggest don’t modify system alias which can help we avoid some
bad execution. If some command or path too long ,you could use alias.
such as, I will use this command “mynet”  to respresent my network
information:

alias mynet=’cat /etc/sysconfig/network-scripts/ifcfg-eth0′

 

but if do above, this alias is temporary,if you want to use the alias
forever, you shoud add the command in ~/.bashrc

 

 美高梅开户网址 11

 

 

 

head && tail

head –output the first part of files

Print  the  first 10 lines of each FILE to standard output.  With more
than one FILE, precede each with a header

giving the file name.  With no FILE, or when FILE is -, read standard
input.

Example:

    head -3 test.file.

        print the first 3 line of test.file

       head test.file   default 10 line

 

in contrast

 

tail — tail – output the last part of files

Ways to use is same as head

 

Question: print 20~30 line of file

head -30 test.txt|tail -11

or

tail -81 test.txt|head -11

 

-f : listen a file tail

Open two terminal, one to write to test.txt

    for example:

       for n in `seq 1000`; do echo $n >> /tmp/test.txt;sleep 1;
done

the other to use tail to listen test.txt

    for example: tail -f /tmp/test.txt

This command is used to listen log file of web ,you can view some
information or exception from the tail of files

    -F the same as -f, but if the file is deleted, it will try too.

 美高梅开户网址 12

 

“|” means pipe

 

 

 

rmdir

rmdir –remove empty directory

    if want more, reference man rmdir.

 

 

 

seq

seq –print a sequence of numbers

   

    seq 1 3

   

 美高梅开户网址 13

 

 美高梅开户网址 14

美高梅开户网址 15

 

 

use “\n” as the separator. you also can use ‘-s’ to change it

 

 美高梅开户网址 16

 

 美高梅开户网址 17

 

 

 

 

vi/vim

 

they are the notepad of linux, if want more, reference book.

 

 

find

This is a vital command, we explain it by examples.

1、find by type and name

find –search for files in a directories

find / -type f -name “att.txt”

/:the directory you think the file searched in

-type: the file’s type

        f:regular file

        d:directory

        …

-name :the file name you want to search

 

-maxdepth +number choose how depth the directory you would search

-pruen: True,if the file is a directory ,do not descend into it. If
-depth is given ,not effective

 美高梅开户网址 18

 

! :not

 

 美高梅开户网址 19

 

 美高梅开户网址 20

 

-o || -or:OR

 美高梅开户网址 21

 

-a or -and :and

 美高梅开户网址 22

 

 

you have fond some files, but you want to view or execute them?

how do to? Following

 

2、find and execute

find / -type f -name “att.txt” -exec ls -l {} \;

you could comprehension as follow:

-exec  COMMAND \

“;” is the bash

 美高梅开户网址 23

 

 

 

But above command also can be replaced by “xargs”, please reference
“xargs”

 

    3、find by time

       find / -type f -mtime -4

-4:the last 4 days

4 :the fourth day

+4 the fourth day ago

 

 

 

 

 

xagrs

xargs –built and execute command lines from standard input

some command may not support pipe,but we can use xargs to standard
input.we use example to explain the command:

 美高梅开户网址 24

 

 

find / -type f -name “att.txt”|xargs cat

use xargs to cat file

 美高梅开户网址 25

 

 

 

 

 

 

grep/egrep

grep –print lines matching a pattern

    args

       -a –text

           process a binary file as if it were text this is equivalent
to the –binary-files=text option

       -c –calculate the matching pattern counts.

       -i –ignore-case

           ignore case distinctions in both PATTERN and input files

        -E : for example: grep -E “A|B|C” means to show A or B C

         -n, –line-number

              Prefix each line of output with the 1-based line number
within its  input  file.   (-n  is  specified  by

              POSIX.)

       -v –invert-match

Invert the sense of matching, to select non-matching lines.  (-v is
specified by POSIX.)

       -A means after N, except for current line we needs ,it will show
after N lines

       -B means before N expect for current lines we need, it will show
before N lines.

       for example, if want to list current and its after 3 lines, you
can use:

    cat test.txt |grep -A 3 30

   美高梅开户网址 26

 

 

similarly,

cat test.txt |grep -B 3 30 

 美高梅开户网址 27

 

    –color=auto the characters which is PATTERN will be show by color,
for example

dmesg | grep -n –color=auto ‘eth0’

 美高梅开户网址 28

 

 

 the result is colorful!

so we can use alias to use it forever

alias grep = ‘grep –color=auto’

add it in your ~/.bashrc

 

 

 

 

sed

sed — sed – stream editor for filtering and transforming text

 we will examples to use this command

    -n:use silent mode, only deal with date will be show screen

    -i:means insert

    Examples:

    1、search 20-30 line a file

   美高梅开户网址 29

 

 

2、search all file named att.txt and replace their content
“oldboyWindows” to ”oldboyLinux” how to do ?

    Firstly, find those files

    find / -type f -name att.txt

 美高梅开户网址 30

 

   

    Secondly, change them in screen,but source files don’t update

find / -type f -name att.txt|xargs sed #oldboyWindows#oldboyLinux#g

           sed s#P1#P2#g

           P1:the content if source files

           P2:the content you want to replace

 美高梅开户网址 31

 

Thirdly: replace in source files, we only need add “-i” after sed,
successful!

 美高梅开户网址 32

 

 

/^S/:begin with S

 

 美高梅开户网址 33

 

/\/$/:/$ is the end of /,because of //,nend to uer \ to change it

 美高梅开户网址 34

 

 

what to do to use ‘sed’ to get you ip address;

use the regex to match, \(.*\) is the content we need,we can use

“\1” to get it at the behind of the second “#”.if you use more one
”\(\)”,you can user “\1” to the get first one, use “\2” to get the
second. if you get nothing, express you regex is not match the
character. Be careful of “-n” and ‘p’

 美高梅开户网址 35

 

 

if you want to insert some content to some files, you can use find and
sed

sed -i ‘1 i ‘

    -i insert ‘1(line number) i(insert)
  (the content you want to
insert)’

some hacker may use it to attract you web

 美高梅开户网址 36

 

 

you can use following ways to solve it.

1、 delete it(recommend because it will not anything including blank
line)

sed -i ‘/the content you want delete/d(delete)’

 美高梅开户网址 37

 

2、 replace it(don’t recommend ,because if will keep blank line)

find /tmp/ -type f|xargs sed -i ‘s#the content you want to
replace#(keep blank)#g’

awk

 

awk — pattern scanning and processing language

    -F –field-separator FS

       Use FS for the input field separator and if want use more one,
user’[]’

       example:

   美高梅开户网址 38

 

      

for example:

1、search 20-30 line a file

 

awk ‘{if(NR>19 && NR<31) print $0}’ test.txt

NR meas line numbers $0 meas all characters

 美高梅开户网址 39

 

/^d/: begin with d

$0:all characters

 美高梅开户网址 40

 

/\/$/:/$ is the end of /,because of //,nend to uer \ to change it

 美高梅开户网址 41

 

 

if want to use more separator, you can use “-F”, for example:

 美高梅开户网址 42

 

Above we use “ ” and “,” two separators, so we can get result we want.

but if the characters have one more “ ” or “,”, what we to do it. We can
use “+” end the ‘]’,it express that if has many separators, we will see
it as one.

 

 美高梅开户网址 43

 

 

histioy

view your history command

history -c :clean all history command

histoty -d +number :delete the number of the history command

!+numer: execute corresponding command

!!: execute the latest command

!+”CHARACTER”: exrcute latest start with “CHARACTER”

 美高梅开户网址 44

 

 

yum series

yum install pagename (-y) :install package name not need interactive

    -y: allow all operate

yum groupinstall “Devolopment Tools” : install page groups, and
pagegroup name must use “”

 

yum grouplist : view how many package your system has installed and
available   

 美高梅开户网址 45

 

 

yum update or yum upgrade: update you system to the newest version

   

 

   

 

SELinux

SELinux has three status :

1、 enforce(default) must  to do some operation

2、 permissive  permit to do some operation but give warning

3、 disabled : don’t manage operation

But we don’t use it in server, so we will close it.

 

update the /etc/selinux/config can change its setting,but this operation
need to reboot

 美高梅开户网址 46

 

getenforce :view current SELinux status

setenforce set the status of SELinux and not neeed reboot

美高梅开户网址 47

 

In this situation: Your server is running ,but you can’t reboot it and
you want to close SELiux, how to do it?

1、 update the /etc/seliunx/config SELINUX=disabled

2、 enforence 0 :change current SELinux status to permissive

So when the next time your system reboot, your SELinux will change to
disabled

This is perfect ways!

 

                     runlevel & init

runlevel:view you system run level

init +number : switch you system level

If your want more, reference Homework: Linux seven pattern of start

 

 

chkconfig

   chkconfig:update and queries runlevel  information for system
service

    chkconfig –list:list all system levels service

    chkconfig –del  +name  delete the system service

    chkconfig –add +name add service on system

    chkconfig –level RUN_LEVEN SERVICE_NAME ON/OFF :set service on   
RUN_LEVEL that you set

    chkconfig SERVICE_NAME ON/OFF :set SERVICE_NAME ON/OFF on all
run_level except for 0 and 6;

 

You also can User setup–system-servide or User the command “ntsysv” to
open system_service windows

 

 

reload or restart

SSH SERVICE:if you update the /etc/ssh/sshd_config, and want it
available, you can user this command to reload the file
“/etc/init.d/sshd reload”.And use this command “/etc/init.d/sshd
restart” to restart sshd service

 

Open/Close the firewall:

    /etc/init.d/iptables stop

/etc/init.d/iptables stop

 

 

 

netstat & lsof

netstat:Print network connections, routing tables, interface statistics,
masquerade connections, multicast memberships

-l –listen

-n –numeric

-t –tcp

-u –udp

-p –program

So we always to use the five params together

 美高梅开户网址 48

 

    -a -all

       We also user -an together

       美高梅开户网址 49

 

losf –list open file

-i: This option selects the listing of files any of whose Internet
address matches the address specified in              i.   If  no
address is specified, this option selects the listing of all Internet
and x.25 (HP-UX) net-

                work files.

    we also use the command “lsof -i:52113” to view the port:52113
status

 

 美高梅开户网址 50

美高梅开户网址, 

 

which

which: show the full path of (shell) commands

for example:

 美高梅开户网址 51

 

 

PATH

we use the command or shell ,but what does the system to search the
command and execute it. This is PATH, is a environmental parameter

 美高梅开户网址 52

 

you command directory in PATH, you can use it in Terminal or shell.

    you can use “PATH=$PATH:/root/oldboy” to add your path,but is
temporary ,if you want to save it forever, to add it in /etc/profile.
and,

if you want user the command on you own, you can add it at ~/.bashrc or
/home/.bash_profile

 

 

il8n

if you want to change you character coding ,you change it in
/etc/sysconfig/i18n

 美高梅开户网址 53

 

you need to use the command  “souce /etc/sysconfig/i18n” ,it will change
in you system now,or it will change an next reboot

you also can user LANG=CH to change it temporary.  

 

you can user “locale” to view the character coding specific information.

 

 美高梅开户网址 54

 

 

chattr && lsattr

 

chattr +i +filename can give a file a limits that don’t do any operate
to it

lsattr +filename view the special limits about a file

 

 

whomi && w

whoami: print effective userid

 美高梅开户网址 55

 

 

w – Show who is logged on and what are they doing

 美高梅开户网址 56

 

 

tree

tree: list contents of directories in a tree-like format

    -L:–level +number show the depth of directories

    -d: list directories only

 

    examples:

       美高梅开户网址 57

 

 美高梅开户网址 58

 

 

 

file

file:determin file type

1、 view file type

file +filenamePath

 美高梅开户网址 59

 

dumpe2fs

dumpe2fs:dump ext2/ext3/ext4 filesystem information

for example:

 美高梅开户网址 60

 

 

tar

-c –create

    create a new archive

-x –extract,–get  

    extract files from a archive

-t –list

    list the contents of an archive

 

-v –verbose

    verbosely list files processed

-f –file=ARCHIVE

    user archive file or device file

 

-C –directory=DIR

        change directory to DIR

-z –gzip

    filter the archive through gzip.

 

-j –bgzip2

filter the archive through bgzip2

 

so we also use those commands

zip:

    tar -zcvf ARCHIVE.tar.gz SOURCE

        create archive from files foo and bar through zip

    tar -zxvf ARCHIVE.tar.bz (-C DIRECTORY)

        extract all files from archive.tar through zip

    tar -ztvf ARCHIVE.tar

        list all files in ARCHIVE.tar verbosely through zip

bgzip2

    tar -jcvf ARCHIVE.tar.gz SOURCE

        create an archive from files foo and bar through bgzip2

    tar -jxvf ARCHIVE.tar (-C DIRECTORY)

        extract all files from archive.tar through bgzip2

    tar -ztvf ARCHIVE.tar

        list all files in ARCHIVE.tar verbosely through bgzip2

    examples:

 

 美高梅开户网址 61

 

 

 美高梅开户网址 62

 

 

 美高梅开户网址 63

 

 

 

cut

cut remove sections from each line of files, default “ ”

-c –character=LIST

        select only these characters

-d –delimiter=DELIM

        use DELIM instead of TAB for field delimiter

-f –field

        select only these field; also print any line that contains no
delimiter character, unless the -s option is specified

-s, –only-delimited

        do not print lines not containing delimiters

for example:

 美高梅开户网址 64

 

 

what to do get your ip address by using “cut”

 美高梅开户网址 65

 

wc

wc print newline, word, and byte counts for each files

    -L –max-line-length

        print the length of  the longest line

     美高梅开户网址 66

 

 

 

ln

ln make links between files

    -s –symbolic

         make symbolic instead of hard links

hard link:

ln SOURCE_FILE HARD_FILE_LINK

symbolic link

ln -s SOURCE_FILE SYMBOLIC_LINK_FILE

 

mkfs

mkfs: build a Linux file system

for example:

    mkfs.ext4 /dev/sdb

 

tr

tr –translate or delete characters

    for example:

 美高梅开户网址 67

 

date

date –print or set system date or time

    -s –set=STRING

       set time described by STRING

    %F –full-date; same as %Y-%m-%d

    %Y year

    %y last two digits of year

    %m month (01..12)

    %d day of month

    %H hour(00..23)

    %M minute(00..59)

    %S second(00..60)

    %w day of week(0..6) 0 is Sunday

    %u day of week(1..7) 1 is Monday

    %T time same as %H:%M:%S

special characters

.: current directory

.. : parent directory

–    cd – : back the directory you open latest

 美高梅开户网址 68

 

>> && > && << && <  

    standard (stdin) input: code: 0 <<(0) or <(0)

    standard output (stdout) code 1 (1)>> or (1)>

 standard error (stderr) code 2 2>> or 2>

2>&1:let let stderr redirect to stdout

for example

 

 

`command`: let the command to execute

 

~:cd ~  redirect home directory

{}:

 

 美高梅开户网址 69

 

; the separator about many commands

 

/:root or path deperator

^: startwith character

$: endwith character

^$:blank line

 

 

 

 

Hotkeys:

Tab: complement command

Ctrl+C stop current process in the front

在CRT中

Ctrl+Shift+C copy

Ctrl+Shift+V paste

Ctrl+d: exit or quit

 

Ctrl+a: move to the first of current line

Ctrl+e: move to the end of current line

Ctrl+u :delete current line

Cthr+r search command in your history

Ctrl+l clean screen

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图