Linux-常用命令-02

Linux-常用命令-02_分隔符

一、文本编辑命令

1.1. more less uniq tee

#-----------------more-----------------#
-u, 禁止下划线;
+<数字>, 从指定数字的行开始显示;
Ctrl+F/B 向下滚动一屏/返回上一屏
= 输出当前行的行号
:f 输出文件名和当前行的行号
#-----------------more-----------------#

#-----------------less-----------------#
less +G /var/log/messages
-l, 搜索时忽略大小写的差异;
-N, 每一行行首显示行号;
#-----------------less-----------------#

#-----------------uniq-----------------#
-c, 在每列旁边显示该行重复出现的次数;
-d, 仅显示重复出现的行列;
-u, 仅显示出一次的行列;
#-----------------uniq-----------------#

#-----------------tee-----------------#
# 把数据重定向到给定文件和屏幕上
# tee指令会从标准输入设备读取数据,将其内容输出到标准输出设备,同时保存成文件
ls |tee -a out.txt| cat -n
ln -sf test test_link 
   4195499 lrwxrwxrwx. 1 xdpp xdpp 4 427 15:55 test_link -> test
#-----------------tee-----------------#

1.2. nc telnet lsof

Linux下开启和关闭Telnet服务

# 关闭telnet服务:
vim /etc/xinetd.d/telnet,将disable=no改成disable=yes
chkconfig telnet off
/etc/init.d/xinetd restart 或者 service xinetd restart
rpm -e telnet-server --nodeps
vim /etc/services    # 注释23号端口

# 开启telnet服务:
chkconfig telnet on 
chkconfig --add telnet
chkconfig --list | grep -i telnet
rpm -qa | grep -i telnet
rpm -ql telnet

# lsof
lsof -i :22
lsof -p PID

# ifconfig
ifconfig eth0 192.168.120.56 netmask 255.255.255.0 broadcast 192.168.120.255

# route / netstat
route -n
route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0
route add default gw 192.168.120.240

netstat -npl
netstat -rn          # 打印路由表信息 route -n
netstat -in          # 提供系统上的接口信息

1.3. tr cut sort

#---------------tr----------------#
-c,反选;
-d,删除所有属于第一字符集的字符;
-s,把连续重复的字符以单独一个字符表示;
-t,先删除第一字符集较第二字符集多出的字符;

echo aa.,a 1 b#$bb 2 c*/cc 3 ddd 4 |tr -d -c '0-9 \n'    # 1 2 3 4
echo "thissss is   a text linnnnnnne." |tr -s ' sn'      # this is a text line.
cat file |tr -d "\r" > new_file                          # 删除Windows文件“造成”的'^M'字符

#---------------cut----------------#
cut -d分隔符 -f列号 
ifconfig eth0 |grep " inet add" | cut -d":" -f2 | cut -d " " -f1

#---------------sort----------------#
-n, 依照数值的大小排序;
-r, 以相反的顺序来排序;
-t <分隔字符>, 指定排序时所用的栏位分隔字符;
-k, 是指定需要排序的栏位;
-u, 忽略相同行使用;
-o <输出文件>, 将排序后的结果存入制定的文件;

1.4. stat touch

Linux下查看和修改文件时间

#---------------stat----------------#
-a, change only the access time;
-m, change only the modification time;
-t, STAMP user [[CC]YY]MMDDhhmm[.ss]
-r, --reference=FILE
-c, 不建立任何文件

#---------------touch----------------#
# touch [参考文件] [真正文件]
touch -r refer.log real.log
touch -c -t 202104252335 real.log
touch -c -d "2021-04-25 23:35:12.00000000 +0530" real.log

二、打包压缩命令与搜索命令

2.1. find

# 基础用法    
find /home ! -name "*.txt"
# find + xargs: argument line too long
find /foo/bar -name '*.mp4' -print0 | xargs -I{} -0 mv {} /some/path 

# 高级用法
find . \( -name "*.txt" -o -name "*.pdf" \)   # 当前目录及子目录下查找所有以.txt和.pdf结尾的文件
find . -regex ".*\(\.txt\|\.pdf\)$"           # 正则

# find . -type 文件类型
find . -type f -atime -7    # -7,7天之内; atime, 访问时间; mtime, 修改时间; ctime, 变化时间;
find . -type f -size -10k

find . -type f -user root -exec chown tom {} \;
find $HOME/. -name "*.txt" -ok rm {} \;    # -ok和-exec行为一样,不过它会给出提示;
find . -type f -mtime +30 -name "*.log" -exec cp {} old \;

# 要忽略的路径参数要紧跟着搜索的路径之后,否则该参数无法起作用
1. find /data/web/ssy/* -path /data/web/ssy/tmp -prune -o -type d -exec /usr/bin/du -sh {} \; |grep '[0-9]G'|sort -rh|head -10
2. find /home/xdp/gaa/log -path "/home/xdp/gaa/log/kafka" -prune -o -type d -regex '.*log/.*' -print -exec rm -rf {} \;

2.2. xargs

# 1. xargs的默认命令是echo, 空格是默认定界符;
xargs 默认是以空白字符 (空格, TAB, 换行符) 来分割记录的
# 2. 通过xargs的处理, 换行和空白将被空格取代;
-n, 选项多行输出;
-d, 可以自定义一个定界符;
-i, 用{}代替传递的数据
-I {},  用{}来代替传递的数据-n[数字] 设置每次传递几行数据

# name name
# name name
echo "nameXnameXnameXname" |xargs -dX -n2

# -0将\0作为定界符,解决/bin/rm Argument list too long.
find . -type f -name "*.log" -print0 |xargs -0 rm -f 
find . -type f -name "*.jpg" -print |xargs tar -czvf images.tar.gz

ls |grep .log |xargs -i mv {} {}.bak
ls |grep .log |xargs -I {} mv {} {}.bak

2.3. 压缩解压命令

# -z, 用Gzip压缩/解压, *.tar.gz; 
# -j, 用Bzip2压缩/解压, *.tar.bz2;
tar -czvf diff.tar.gz /diff
tar -xzvf diff.tar.gz -C /diff    # 指定解压目录 -C
tar -t diff.tar.gz                # -t, 查看压缩包内容
tar -czvf myfile.tar.gz --exclude=home/logs home

# zip [选项] 源文件
zip -q -r html.zip /home/html  
zip -r /opt/var.zip /var -x "*.log"  # -x,排除"*.log"
# unzip 
unzip -d /home/html html.zip
unzip -v abc.zip

# gzip [选项] 源文件  
注:压缩文件生成,但是源文件也消失了
gzip -c anaconda-ks.cfg >anaconda-ks.cfg.gz # 将压缩数据输出到标准输出中, 并保留源文件;
# gunzip file.gz

三、grep awk sed vim

3.1. grep

# grep [选项] "搜索的内容" file
# -f,根据模式文件处理;-v,反选;
grep -v -f a.txt b.txt    # 输出b文件中在a文件不同的行;

# -E,使用ERE;-o,--only-matching;
grep -E -v "^$|^#" /etc/httpd/conf/httpd.conf
grep -Eo "(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"

# -l,列出文件内容符合指定的范本样式的文件名称;
# -n,在显示符合范本样式的那一列之前,标示出该列的编号;
# -i,忽略字符大小写的差别;
# -o,only只显示匹配的;
# -A num, After;
# -B num, Before;
# -C num, 前后各num行;

# egrep
-c, 只输出匹配的行数
-v, 反向匹配

3.2. sed

从文件或管道中读取一行,处理一行,输出一行;再读取一行,再处理一行,再输出一行,直到最后一行。每当处理一行时,把当前处理的行存储在临时缓冲区中,称为模式空间(PatternSpace);

  • linux中sed的用法
  • Sed常用实例总结
Usag: sed [选项] '模式1动作1; 模式2动作2;...' 文件
# 选项:
1. -n --only, 只输出命令匹配的内容(不显示模式空间内容);     4. -r, --regex开启支持扩展正则;  
2. -i, 修改结果直接应用于文件;                            5. -e, 多个命令组合 或者 用`;`分割;     
3. -f scriptfile, 从sed脚本读入sed操作;          

# 模式:
1. /pattern1/,/pattern2/    # 查询从匹配模式1~模式2之间的行    
2. /pattern/pattern/        # 查询包含两个模式的行
3. x,/pattern/              # 从与x行~与pattern匹配行之间的行  

# 动作(command):
1. i\str  a\str  c\str  # 在指定行前插入//在指定行后追加//行替换用c后边的字符串替换原数据
2. r  w                                   # 读入//写入;
sed '/^test/a\this is a test line' file   # 将 this is a test line 追加到 以test 开头的行后面;
sed -i '2a\this is a test line' tst.conf  # 在 test.conf 文件第2行之后插入 this is a test line
sed '1,2r /etc/issue' /etc/fstab
sed '/oot/w /tmp/oot/txt' /etc/fstab      # 所有包含oot的行都被写入file里;

3. d  s  p  q  删除//替换//打印//退出
sed -e '1,5d' -e 's/test/check/' file      # 删除1,5行,替换每行第一个test; 
sed '/^$/d' file                           # 删除空行  
echo aaa BBB | sed -n 's/\([a-z]\+\) \([A-Z]\+\)/\2 \1/p'  # BBB aaa
sed -n 's/^root/#&/p' passwd                               # 注释掉以root开头的行
sed -i '/^[[:space:]]*#/d' nginx.conf

4. g, 全局替换,将保持缓冲区的内容替换到模式缓冲区;
5. G, 将保持缓冲区的内容追加到模式缓冲区;
6. h, 拷贝模板块的内容到内存中的缓冲区;
7. H, 追加模板块的内容到内存中的缓冲区;
sed -i 's/SELINUX=enforcing/SELINUX=disable/' /etc/selinux/config     # setenforce 0

8. n, 读取下一个输入行,用下一个命令处理新的行而不是用第一个命令;
9. N, 追加下一个输入行到模板块后面并在二者间嵌入一个新行,改变当前行号码;

3.3. awk

关于grep、sed和awk的基础用法

Linux-常用命令-02_sed_02

Usag: awk [选项] '条件1{动作1} 条件2{动作2} ...' 文件
# 内部变量
1. $0, 当前读入整行数据;                        
2. $n, 当前读入行的第n个字段,第n列;

3. 列分隔符
  FS, Field Separator 输入字段(列)分隔符,默认是空格或制表符 BEGIN{FS=":"};
  OFS, 输出字段(列)分隔符,默认是空格;

4. 行分隔符
  RS, Record Separator 输入记录(行)分隔符,默认是换行符\n; 
  ORS, 输出记录(行)分隔符,默认是换行符\n;                      

5. 列号/行号 
  NF, Number Field 统计当前记录中字段(列)个数,列号;
  NR, Number Record 行号,当前处理的文本行的行号;
  FNR,	Field Number Record 同NR,各文件分别计数的行号;

# Example
awk 'BEGIN{FS=":";OFS=":"}{print $1,$2}' /etc/passwd |head -n5    # root:x
awk -F: '{print "%-12s %-6s %-8s\n", $1, $2, $NF}'
cat /etc/passwd |grep "/bin/bash" |awk 'BEGIN{FS=":"}{printf $1 "\t" $3 "\t行号:"NR "\t字段数:" NF "\n"}'
------------------------------------------------------------------------------------------
awk -F ":" '{ if($3<500) { print $1,"系统用户" } else{ print $1,"普通用户" }}' /etc/passwd
awk -F ':' 'BEGIN{count=0;} {name[count]=$1; count++;} END{for(i=0; i<NR; i++) print i, name[i]}' /etc/passwd
awk '$1==2 {print $1,$3}' log.txt
netstat -n |awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
#!/bin/sh
# stress-1.0.4-16.el7.x86_64.rpm    /usr/bin/stress
# ln -sf /usr/bin/stress /root/java_vm
ps -ef | grep java_vm|grep -v grep|awk '{print $2}'|xargs -i kill -9 {}
nohup /root/java_vm -c 6 -t 86400s &

四、Extra

4.1. 网址

4.2. rpm

RPM:(红帽软件包管理器) 相当于windows 的控制面板的软件管理;

rpm -ivh filename.rpm    
rpm -Uvh filename.rpm       # 升级         
rpm -e filename.rpm         # --nodeps 不检查依赖性 卸载软件✔, -e,–erase
rpm -qf filename            # 查询文件属于哪个包

rpm -qd filename            # 查询所安装的包的帮助文件
rpm -qi filename.rpm        # 查询包描述信息 -p(查未安装,包全名)

rpm -qc filename            # 查询所安装的包的配置文件
rpm -ql filename.rpm        # 列出包文件信息 -p(查未安装)
rpm -qa | grep filename     # 查询所安装的包的名称

rpm --import /etc/pki/rpm-gpg/RPM*
rpm2cpio xxx.rpm | cpio -div

4.3. yum

# 可以联网的机器
# yumdownloader is a program for downloading RPMs from Yum repositories
yum install yum-utils -y
mkdir /tmp/ansible
yumdownloader --resolve --destdir /tmp/ansible ansible
yumdownloader --resolve --destdir /tmp/ansible createrepo
tar -czvf ansible.tar.gz /tmp/ansible

# 内网机器
# 上传tar包,制作离线yum源
cd /tmp/ansible
rpm -ivh deltarpm-3.6-3.el7.x86_64.rpm
rpm -ivh python-deltarpm-3.6-3.el7.x86_64.rpm
rpm -ivh createrepo-0.9.9-28.el7.noarch.rpm
cd /tmp
createrepo ansible

vim /etc/yum.repos.d/ansible.repo
[ansible]
name=ansible
baseurl=file:///tmp/ansible
gpgcheck=0
enabled=1

yum install ansible -y
yum repolist all/enabled/disables    # 列出软件仓库
yum list all/installed               # 列出仓库所有软件/已安装的
yum info 包名称
yum history                    # 查看历史
yum search Package
yum install 包名称
yum reinstall 包名称            # 卸载包
yum update 包名称
yum remove 包名称               # 慎用❗❗ 会把依赖的一些包也删掉  rpm -e --nodeps nginx
yum clean all
yum check-update

yum-config-manager --add-repo http://www.example.com/example.repo
yum-config-manager --enable/--disabled reponame

# 常用工具:(yum install epel-release.noarch)
    yum install lrzsz gcc gcc-c++ gdb pcre pcre-devel zlib zlib-devel ruby \
    openssl openssl-devel patch wget curl bash-completion \
    lsof tcpdump nc nmap htop screen vim git redhat-lsb net-tools \
    vsftp tree

4.4. ssh

# scp
scp -r remote_username@remote_ip:remote_folder local_folder 
scp -r remote_ip:remote_folder local_folder 
scp root@www.runoob.com:/home/root/others/music /home/space/music/1.mp3
# ssh-keygen
ssh-copy-id remoteuser@remoteserver

[xy@VM-0-4-centos ~]$ sftp
usage: sftp [-1246aCfpqrv] [-B buffer_size] [-b batchfile] [-c cipher]
          [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-l limit]
          [-o ssh_option] [-P port] [-R num_requests] [-S program]
          [-s subsystem | sftp_server] host
       sftp [user@]host[:file ...]
       sftp [user@]host[:dir[/]]
       sftp -b batchfile [user@]host

# 增加用户
useradd sftpuser -s /sbin/nologin
chown root:sftpuser /home/sftpuser
chmod 755 /home/sftpuser

# 更改sshd_config 配置
# override default of no subsystems
# Subsystem	sftp	/usr/libexec/openssh/sftp-server
Subsystem	sftp	internal-sftp

# settting on a per-user basis
Match group sftpuser        # Match [User|Group] sftp 
ChrootDirectory %h          # %h代表用户家目录 %u代表用户名,也可以直接指定目录/var/sftp
ForceCommand internal-sftp  # 强制使用系统自带的 internal-sftp 服务 这样用户只能使用ftp模式登录
AllowTcpForwarding no       # 禁止使用端口转发
X11Forwarding no

# 重启sshd 服务
# sftp命令
lpwd                               Print local working directory
lls [ls-options [path]]            Display local directory listing
put [-afPpRr] local [remote]       Upload file
get [-afPpRr] remote [local]       Download file

作者:anyu967