Linux 应用小记

本文详述了Linux常用命令,包括文件操作、进程管理、网络通信、文本处理等多个方面。介绍了如何创建软链接、终止进程、传输文件、使用awk进行文本处理,以及sed、grep、diff、sort等工具的用法。此外,还涵盖了Vim编辑器的操作技巧和Linux终端快捷键。内容实用,适合Linux系统管理员和开发者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux常用命令

操作系统

  • 软连接
    • ln -s 需要用的文件路径 被替代的文件路径(绝对路径):
      • 举例1 ln -s /data/docker /var/lib,使用/data/docker文件夹来代替/var/lib/docker文件夹存储数据(也就是/var/lib/下的docker文件夹其实是/data/下的docker文件夹)
      • 举例2 ln -s /mnt/server_139/ccy/ChatGLM-Tuning/data /data/ccy/ChatGLM-Tuning/
    • 删除软连接:rm xxx_link,只会删除软连接;unlink,还会删除对应的文件
  • 主机名
    • hostname 只有主机名
    • hostnamectl 更详细
    • uname -a
  • lsof

程序、进程

  • jobs -p:查询当前用户正在进行的进程
  • kill:根据pid来终止进程
    # 终止GPU进程
    lsof /dev/nvidia* | awk '{print $2}' | uniq | xargs -I {} kill -9 {}
    
    # 终止指定进程
    ps -aux | grep dog | awk '{print $2}' | xargs -I {} kill -9 {}
    ps -aux | grep http.server | awk '{print $2}' | xargs -I {} kill -9 {}
    
    # 根据指定的进程名称来 kill 前100行,使用 awk 从 ps 的列表中取出第2列(pid列)
    ps -ef | grep 'offline_spu_bmc_pipeline' | head -100 | awk '{print $2}' | xargs -I {} kill -9 {}
    
  • killall:根据匹配名称来终止进程
    rm -rf /home/noah/heyeAgent /opt/heyeAgent; killall heyeAgent
    

传输、密钥

  • 传输命令
    • scp
    # scp上传、重命名上传文件
    scp xxx_file chenchongyuan@10.24.22.251:/home/chenchongyuan/
    scp xxx_file chenchongyuan@10.24.22.251:/home/chenchongyuan/yyy_file
    # scp下载
    scp chenchongyuan@10.24.22.251:/home/chenchongyuan/xxx_file .
    scp zhuzz@10.80.140.22:/home/disk2/zhuzz/ (密码:zhuzz507)
    # scp -r则是传输目录
    scp -r zhuzz@10.80.140.22:/home/disk2/zhuzz/one_dir/ .
    
    • rsync
    • wget
      • -O 为下载文件重新命名;-P 指定下载路径;-b 后台下载;-c 断点续传;-i 从文件中的多个路径(一行一个路径)来下载多个文件
    # wget下载
    wget 10.24.22.251:8981/home/chenchongyuan/xxx_file
    
    • rz;rc
    • nc
    # 从本地上传文件到开发机
    # step 1:在接收端执行
    nc -l 8998 > infer_res
    
    # step 2:在 PaddleCloud 上执行,其中的 IP 为接收端机器的
    nc 10.24.22.251 8998 < infer_res
    
  • 生成密钥
    • ssh-keygen -t rsa,3次回车
  • ssh 服务
    • 启动 ssh 服务:service ssh start
  • 远程登录服务器
    • 登录跳板机
      • ssh chexxx@relay.bxxxx-int.com -oHostKeyAlgorithms=+ssh-rsa
    • 登录开发机
      • ssh chexxx@10.24.xx.251
#!/usr/bin/expect

# 免密登录开发机
# turn off expect's time-out
set timeout -1

# 邮箱前缀
set USER "chexxx"
# 邮箱密码
set MAIL_PASSWORD "xxxx223#"
# [可选]开发机地址, 如:user@host
set HOST "chexxx@xx.xx.xx.251"
# [可选] 开发机密码
set PASSWORD "Jxxxxx."
# 登录relay
spawn ssh $USER@relay.bxxxx-int.com -oHostKeyAlgorithms=+ssh-rsa
# 打开调试模式
# exp_internal 1

expect {
    -re "password:" {
        # 输入邮箱密码,登陆relay
        send "$MAIL_PASSWORD\r"
        exp_continue
    }

    # 自动登录开发机
    -re "-bash-bxxxxu-ssl*" {
        if { "$HOST" != "" } {
            send "ssh -o ServerAliveInterval=30 --silent $HOST\r"
            if { "$PASSWORD" != "" } {
                expect -re "password:" { send "$PASSWORD\r" }
            }
        }
    }
}
# 关闭调试模式
# exp_internal 0
interact
exit
  • 绕过堡垒机,通过docker传输
    • 需要将本机(root权限)的公钥 id_rsa.pub 放在目标节点的 docker 虚拟机的 root/.ssh/authorized_keys 文件中
    • 启动 ssh 服务后,进行传输:rsync -avzP /data/Megatron-LM/ root@172.24.129.136:/data/
  • 从服务器下载文件到本地
    • 先在服务器上执行 python -m http.server xxxx_port,然后再本地浏览器中打开(需要获取服务器ip):服务器ip:xxxx_port

用户、权限

  • su
    • su xxx:切换到xxx用户,环境变量不变,路径不变
    • su - xxx:切换到xxx用户,环境变量改变为xxx的,路径改变为家目录
  • useradduseradd 与 adduser 的区别
    • step1 useradd -m -s /bin/bash test_user:-m 强制创建用户目录;-s /bin/bash 指定用户的 shell 为 bash(默认为sh)
    • step2 pass test_user:设置用户的密码
  • sudo 权限
  • sudo su
  • groupadd
  • usermod
  • newgrp xxx:重新登录到 xxx 用户组

解压、压缩

  • linux tar.gz zip 解压缩 压缩命令
    • 解压文件:tar -xzvf file.tar.gz
    • 压缩目录:tar -czvf 压缩文件名.tar.gz 要压缩的文件夹名;指定目录:tar -czvf 压缩文件名.tar.gz 要压缩的文件夹名 -C xxx_dir
    • 显示文件内容:tar -tvf
  • Linux命令之压缩zip
    • unzip -v test.zip:显示压缩包的内容(不进行解压),-l 类似(显示的内容比 -v 更简洁)
    • unzip test.zip -d /root/source/-d 后必须跟指定的路径
    • -q 不显示解压过程
    • -o 表示不询问用户,覆盖原有文件
    • 压缩文件夹中的文件:zip -r dir.zip dir dir 为要被压缩的文件夹

文本处理

  • awk

    • awk工作流程是这样的:1、先执行BEGIN;2、然后读取文件,读入有/n换行符分割的一条记录,然后将记录按指定的域分隔符划分域,填充域,$0则表示所有域、 1 表示第一个域、 1表示第一个域、 1表示第一个域、n表示第n个域,随后开始执行模式所对应的动作action。接着开始读入第二条记录······直到所有的记录都读完;3、最后执行END操作
    • 文件添加列:
      • 在开头添加一列row_number:awk '{print NR,"\t"$0}' file_1 > file_2
      • 在末尾添加一列固定值:awk '$0=$0"\t20161020"' file_1 > file_2
    • 参考文档
    # 查看文件中为特定值的内容
    awk -F '\t' '{if($4!="PASS"){print}}' xxx_file
    awk -F '\t' '{if($4=="PASS"){print}}' xxx_file | wc -l
    
    # 第2列包含th内容时,输出第2、4列
    awk '$2 ~ /th/ {print $2,$4}' xxx_file
    # 以:为分隔符,第3列包含9时,输出第1、3、4列
    tail -5 /etc/passwd | awk -F : '$3 ~ /9/ {print $1,$3,$4}'
    
    # 查看文件的列数
    head -1 xxx_file | awk -F '\t' 'END{print NF}'
    
    # 将一列值求和
    cut -f2 xxx_file | awk '{sum+=$1}END{print sum}'
    
  • cut

    • cat /etc/passwd | cut -d: -f5--d 后跟分隔符(这里是 :),-f 后跟字段(2,3 表示取出第2和第3个字段;N-M 表示从第N个字段到第M个字段,这两个均可省略:N省略表示第一个字段、M省略表示最后一个字段)
    • -c:根据字符来切,如 cut -c1-3 表示切第1到第3个字符
    • -b-bn
    • cut
  • 显示指定行的内容

    • sed:sed -n 'X,Yp' filename,从第X行开始,显示Y行,即显示到(Y-1)行,也就是显示X~(Y-1)行
    • head/tail:cat filename | tail -n +X | head -n Y,从第X行开始,显示Y行,即显示到(Y-1)行,也就是显示X~(Y-1)行
    • tail -n +3 /etc/passwd :不要前2行(输出从第3行到最后一行)。简写:tail +3 /etc/passwd
    • head -n -3 /etc/passwd:不要最后3行(输出从第1行到倒数第4行)
  • grep

    • -n:输出行号,grep -n 't[ae]st' xxx_file
    • -r:搜索目录而不是文件,grep -r 'xxx' . 表示在当前目录及其子目录下搜索文本内容 xxx
    • -l:输出含有pattern的文件,grep 'y=3' -rl xxx_dir
grep "chosed.*哎呀" dpo_data.txt -c

# pag '8981'
ps aux | grep '8981'
  • shuf

    • -i 指定整数数字范围: -i 1-100 表示 1-100 的闭区间
    • -e 指定字符范围:-e a 积极 nuos 表示随机的范围为【a、积极、nuos】
    • -r 是否可重复采样
    • -n 指定随机多少个(若不指定 -r 可能达不到这么多的数量)
    • -o 后跟输出的文件名
    • -z 不换行
    • 举例:
      • shuf -i 1-10 -r -n 20 -o /data/test.txt
      • shuf -e a 积极 nuos -z -r -n 10 -o /data/test.txt
      • shuf /data/test.txt 将文件随机输出,shuf -n 5 /data/test.txt 随机输出文件的 5 行
  • diff

    • -c:显示全部内容,并标出不同之处
    • -u,-U<列数> 或 --unified=<列数>:以合并的方式来显示文件内容的不同
    • -<行数>:指定要显示多少行的文本。此参数必须与 -c-u 参数一并使用
    • -i 或 --ignore-case:不检查大小写的不同
    • -q 或 --brief:仅显示有无差异,不显示详细的信息
    • -b 或 --ignore-space-change:不检查空格字符的不同
    • -B 或 --ignore-blank-lines:不检查空白行
    • -r 或 --recursive:比较子目录中的文件
    • -t 或 --expand-tabs:在输出时,将tab字符展开
    • -T 或 --initial-tab:在每行前面加上tab字符以便对齐
    • -w 或 --ignore-all-space:忽略全部的空格字符
    • -y 或 --side-by-side:以并列的方式显示文件的异同之处
    • -W<宽度> 或 --width<宽度>:在使用 -y 参数时,指定栏宽
    diff a.txt b.txt -y -W 170
    
  • sort

    • 默认情况:默认是用每行开头的第一个字符来进行排序
    • -c:检查文件是否已经按照顺序排序
    • -f:忽略大小写
    • -b:忽略每行前面的空白部分
    • -d:排序时,处理英文字母、数字及空格字符外,忽略其他的字符
    • -i:排序时,除了040至176之间的ASCII字符外,忽略其他的字符
    • -t:指定分隔符,默认分隔符是制表符
    • -k [n,m]:按照指定的字段范围排序。从第 n 个字段开始,到第 m 个字(默认到行尾)。比如:sort -t ":" -k 3,3 /etc/passwd
      • -k 3.1,3.1 以第3列的第一个字符到第3列的第一个字符排序,-k 4.1,4.3 以第4列的第一个字符到第4列的第3个字符排序
    • -n:以数值型进行排序,默认使用字符串排序。比如:sort -n -t ":" -k 3,3 /etc/passwd
    • -r:反向排序
    • -u:删除重复行,就是 uniq 命令
    • -h:按照人类习惯阅读方式比较文件大小
    • -M:按照月份来排序
    • 合并两个文件并排序:sort aa bb > cc
  • uniq

    • 默认情况:只会去除相邻两行的重复文本,通常在 sort 之后使用
    • -c:统计重复的次数
    • -d:只显示重复的文本
    • -u:只显示唯一的文本
    • -i:忽略大小写
    • -f N:忽略前 N 个字段(字段间用空白字符分隔)
    • -s N:不比较前 N 个字符

显示

  • 后台运行
    • nohup sh run.sh > train_log 2> error_log
    • nohup sh submit.sh > mr_log 2>&1 &
  • tmux
    • 参考1
    • 参考2
    • tmux new -s xxx_name
    • tmux ls
    • tmux a -t xxx_name
    • 退出tmux窗口:先按ctrl-a/ctrl-b,再按d(松开ctrl)

文件

  1. 查找文件:find / -name xxx_file/ 表示在根目录下查找
    1. find / -name xxx_dir -type d/ 表示在根目录下查找
  2. 查看文件类型:file、iconv等文件相关命令
  3. 复制 cp
    1. cp -a 等价于 -drp:1、复制链接 -d;2、递归复制文件夹 -r;3、保留文件的原始信息(修改时间等)-p
    2. cp -ruv xxx1/* xxx2/:-u 表示本地xxx2中时间更新的文件不会被复制过来
  4. 拆分 splitLinux命令之分割文件split
    1. 默认情况:默认是每 1000 行切割成一个小文件;切割后文件的默认前缀是 x,默认按照 xaa、xab、xac 文件名顺序
    2. 根据文件大小来分割:split -b 10M log.txt,可以指定 1024 的幂:K、M、G 等,也可以指定 1000 的幂:KB、MB、GB
    3. 根据行数来分割:split -l 2 log.txtsplit -2 log.txt
    4. 指定拆分后文件的前缀名:split -行数 待切割文件 切割后的小文件名,比如:split -2 log.txt log_split.txt
    5. 指定拆分后文件的后缀名:split -2 --additional-suffix=.split-txt log.txt
    6. 使用数字命名:split -d 待切割文件
    7. 文件合并:cat xaa xab > file_merge;合并后的校验(对于传输大文件):md5sum file_merge
    # 根据行数拆分(-l),拆分的下标用数字命名(-d),指定拆分文件前缀(split_file.index_)
    split -l 1500 -d xxx_file split_file.index_
    

硬件

  1. 查看系统盘容量
    1. df -h
    2. du
      1. du -sh /data/xxx 查看xxx文件夹的总占用量
      2. du -h --max-depth=1 查看每个文件夹的大小

Vim

  • PowerVim
  • vim
  • vim visual
  • 缩进
    • 方法1
      • a> 第a行向右缩进
      • a>b 从第a行开始的b行向右缩进
      • a,b> 从第a行到第b行向右缩进
    • 方法2:visual line 模式
      • shift + v 组合键进入 Visual Line 模式,通过光标来选择需要移动的行,然后使用 >< 进行移动(移动整行)
    • 方法3:visual block 模式
      • ctrl + v 组合键进入 Visual Block 模式,通过光标来选择需要移动的行,然后使用 >< 进行移动(可以从代码的中间部分进行移动)
  • 多行注释(多行注释需要将vim切换为可视化模式-- VISUAL BLOCK --)
    • 添加注释
      1. 按下 Ctrl + v,进入 --VISUAL BLLOCK-- 模式;
      2. 方向键选择则需要注释的行;
      3. 输入大写字母I(小写模式下:shift+i),再输入注释符(//#);
      4. Esc 退出,注释符就会出现在行首;(按一下Esc键,需要等待片刻,才会全部注释,按两下Esc键,立即全部注释)
    • 取消注释
      1. 按下 Ctrl + v ,进入 --VISUAL BLLOCK-- 模式
      2. 方向键选中需要取消的行
      3. 按下 d 将注释符删除
  • 统计
    • :%s/pattern//gn 在文件中统计匹配的个数(一行中有多个匹配,也算多个)
    • :%s/pattern//n 去掉 g 这个参数,就是统计成功匹配的行数(一行中有多个匹配,只算一个)
    • :10,88s/pattern//gn 也可以限定在某个范围行内统计(%表示在整个文件范围内搜索)
    • :s/pattern/gn 在当前行上统计匹配的个数
    • :%s///gn 利用上次搜索的pattern来统计。小trick:在当前光标处,敲 *,自动搜索当前光标所在位置的词,然后用这个命令,就可以避免敲这个词了,可直接统计了
  • 替换
    • :%s/pattern/xxx 在文件中统计匹配的文本 pattern 替换为 xxx。举例::%s/\mnt\/ttt/\/data\/ccy\/sss,把 \mnt\ttt 文件夹路径替换为 \data\ccy\sss(需要在文件路径分隔符 / 前添加转义符号 \
  • Bug 相关
    • Vim: Warning: Output is not to a terminal:因为某些错误操作导致terminal“卡死”,其实是进入了vim编辑状态,输入 Escshift+zz 即可退出

网络与通信

  • 网络服务端口
    • netstat -tlunp
    # 查询活跃的网络服务接口:t显示TCP连接,u显示UDP连接,l显示监听状态的连接,n以数值形式显示端口号(而不是使用服务名进行解析)
    netstat -tulngrep "port"
    # 
    lsof -i:xxx_port
    
  • 请求
    • curl
      • 对于过长的数据,可以放在一个文件(如:xxx.json)里面,然后使用 @ 来获取文件中的数据(比如:curl xxx -d @xxx.json);也可以从管道 - 中获取(比如:cat xxx.json | curl xxx -d @-
      • 请求api:curl -X POST "http://10.215.209.144:2003" -H 'Content-Type: application/json' -d '{"prompt": "空气炸锅怎么使用", "history": []}'

crontab

# 打开crontab配置
crontab -e

Linux 终端

Ctrl + c:结束正在运行的程序【ping、telnet等】
Ctrl + d:结束输入或退出shell
Ctrl + s:暂停屏幕输出
Ctrl + q:恢复屏幕输出
Ctrl + l:清屏,等同于Clear

Used command

cat diff_train_set | cut -f2 | LANG=utf-8 sort | uniq -c > en
sort en -n -r -o en_sort
cat yugu_terms | awk -F"\t" '{if($2=="-"){print}}' | wc -l
ps aux | grep 'recall_seq.py'
watch -n 1 nvidia-smi
grep '.ke.com' x.htm > data
awk -F"\t" '{print "1\t"$1}' input_file

cmp -l file1 file2
split 
diff file1 file2 -y
cat file | tee new_file

cat h8w_lpa_lextag_noN | cut -f2 | sort | uniq -c | sort -n
awk -F"\t" '{if($2==1 && $3==1){print}}' file

iterm2

在这里插入图片描述
在这里插入图片描述

  • iTerm2 光标按照单词快速移动设置
    在这里插入图片描述
    在这里插入图片描述

  • clear清楚历史记录(下面二选一进行操作)
    在这里插入图片描述
    在这里插入图片描述

  • iTerm2 设置根据单词删除

    • Preference > Profiles > Keys > Key Mappings > 左下角的 + 号新增键位绑定的映射,录入快捷键:option + backspace,Action:Send Hex Code,Code:0x17
  • 3.5.2新版本会出现选中框

  • 插件

    • 历史命令提示

Zsh

  • 安装zsh终端(ubuntu,且有root权限时,【参考文章】
    # 前置:可能需要先更新
    [sudo] apt-get update
    
    # 安装zsh
    [sudo] apt-get install zsh -y
    
    # 然后就是安装oh-my-zsh,url链接:https://ohmyz.sh/#install
    sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
    
    # 合并上面的命令
    apt-get update && apt-get install zsh -y && sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
    
  • 常用插件(安装好的插件一般放在 ~/.oh-my-zsh/custom/plugins/ 下)
    • zsh-autosuggestions(链接:https://github.com/zsh-users/zsh-autosuggestions/blob/master/INSTALL.md)
    # step1: 先clone
    git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
    # step2: 把插件名字添加到~/.zshrc配置文件中,zsh-autosuggestions
    
    • zsh-syntax-highlighting(链接:https://github.com/zsh-users/zsh-syntax-highlighting/blob/master/INSTALL.md)
    # step1: 先clone
    git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
    # step2: 把插件名字添加到~/.zshrc配置文件中,zsh-syntax-highlighting
    
  • .zshrc
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
#ZSH_THEME="robbyrussell"
ZSH_THEME="ys"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment one of the following lines to change the auto-update behavior
# zstyle ':omz:update' mode disabled  # disable automatic updates
# zstyle ':omz:update' mode auto      # update automatically without asking
# zstyle ':omz:update' mode reminder  # just remind me to update when it's time

# Uncomment the following line to change how often to auto-update (in days).
# zstyle ':omz:update' frequency 13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS="true"

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# You can also set it to another string to have that shown instead of the default red dots.
# e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f"
# Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765)
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(
    git
    zsh-autosuggestions
    zsh-syntax-highlighting
)

# Add my new version git path (before `source $ZSH/oh-my-zsh.sh`)
export PATH=$PATH:/usr/local/git/bin

source $ZSH/oh-my-zsh.sh

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

export LC_ALL=en_US.UTF-8

# network proxy
export https_proxy=http://172.19.57.45:3128
export http_proxy=http://172.19.57.45:3128
export GIT_SSL_NO_VERIFY=1
export TERM=xterm


# hmpclient
PATH=$PATH:$HOME/.local/bin:$HOME/bin
export PATH
PATH=/home/chenchongyuan/.hmpclient/bin:$PATH
export PATH
PATH=/home/chenchongyuan/.hmpclient/spark-client/bin:$PATH
export PATH


# icafe cli
export PATH="$HOME/.icafe/bin:$PATH"


# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/home/chenchongyuan/miniconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/home/chenchongyuan/miniconda3/etc/profile.d/conda.sh" ]; then
        . "/home/chenchongyuan/miniconda3/etc/profile.d/conda.sh"
    else
        export PATH="/home/chenchongyuan/miniconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<


# jumbo
[[ -s "/root/.jumbo/etc/bashrc" ]] && source "/root/.jumbo/etc/bashrc"


### My Custom Alias
alias wl="wc -l"
alias h1="head -1"
alias h3="head -3"
alias h5="head -5"
alias t1="tail -1"
alias t3="tail -3"
alias t5="tail -5"
alias c1="cut -f1"
alias c2="cut -f2"
alias c3="cut -f3"
alias c4="cut -f4"
alias c5="cut -f5"

alias sq="sort | uniq"
alias sqd="sort | uniq -d"
alias squ="sort | uniq -u"

alias tf="tail -f"
alias lr="ll -tr"
alias ds="du -sh"
alias cpr="cp -r"

alias pag="ps aux | grep"

alias ww="wget"
alias q="df -h"
alias f="free -g"
alias p="python"

# python
alias pt="python -m http.server 8981"
alias pt2="python -m http.server 8982"
alias pt3="python -m http.server 8983"
alias pt4="python -m http.server 8984"
alias pt5="python -m http.server 8985"

# nvidia
alias ns="nvidia-smi"
alias wns="watch -n 1 nvidia-smi"

# hadoop
alias hfs="hadoop fs -conf ~/configuration/hadoop/hadoop-site-wolong.xml"
alias hls="hadoop fs -conf ~/configuration/hadoop/hadoop-site-wolong.xml -ls"
alias hget="hadoop fs -conf ~/configuration/hadoop/hadoop-site-wolong.xml -get"
alias hgm="hadoop fs -conf ~/configuration/hadoop/hadoop-site-wolong.xml -getmerge"
alias hput="hadoop fs -conf ~/configuration/hadoop/hadoop-site-wolong.xml -put"

# conda
alias cel="conda env list"
alias cda="conda activate"
alias clg="conda list | grep"

# mysql
alias sql_szr="mysql -h 10.1xx.1xx.45 -P11110 -udigital_faq_test -p'passwor!d' -Ddigital_faq -A --default-character-set=utf8"
alias sql_szrlog="mysql -h sxxxtbns.rmblive-bmi0001-offline.xxx -udh_offline_r -p\@pass=word\!ol -P11110 --default-character-set=utf8"
alias sql_szrscript="mysql -h smartbns.cecommysql-bmi0000-offline.xxx -P11110 -ujingtao01_r -p'password' -Dscript_center -A --default-character-set=utf8"
alias sql_dh="mysql -h sxxxtbns.huibomysql-bmi0002-offline.xxx -P11110 -udh_strategy_r -p'password+aJFg' -Ddigital_faq -A --default-character-set=utf8"
alias sql_faq_off="mysql -h 'xxx-dev.bcc-bdbl.xxx.com' -P11110 -uroot -p'password@123' -Dfaq_server -A"
  • .vimrc
set nu
syntax on

终端颜色配置

  • 提示符颜色
# vi ~/.bashrc
PS1="\[[\[\e[91;40m\]\u\e[93;40m\]@\h \[\e[94;40m\]\w\[\e[0m\]]\\$ "
PS1="\[[\[\e[91;40m\]\u@\h\e[93;40m\] \[\e[94;40m\]\w\[\e[0m\]]\\$ "
# source ~/.bashrc

conda

# 查看当前环境下的软件包
conda list

# 查看已有的环境
conda env list

# 进入虚拟环境
conda activate env_xxx
# 退出虚拟环境
conda deactivate

# 查看环境的基本信息
conda info

## 创建环境
# -n 也就是 --name
# 创建一个新环境:不含有任何软件包
conda create -n env_xxx

# 创建一个新环境:指定Python版本,以及需要的软件包(numpy, pandas, torch)
conda create -n env_xxx python=3.10 numpy, pandas, torch

# 创建一个新环境:指定Python版本,以及需要的软件包(指定anaconda表示与base环境相同,会下载base中有的全部软件包)
conda create -n env_xxx python=3.10 anaconda

# 创建一个新环境:从已有的环境克隆(从env_xxx_1克隆出env_xxx_2)
conda create -n env_xxx_2 --clone env_xxx_1

## 删除环境
conda env remove -n env_xxx -y

hadoop

  • 基本命令
# 通过 -D 参数来指定一些值,比如:fs.default.name、hadoop.job.ugi

# -ls: 查看目录
hadoop fs -D fs.default.name=afs://wolong.afs.com:9902 -D hadoop.job.ugi=username,password -ls /user/sasd-goods/goods-search/xxy/mr_jobs/

# -get: 从集群下载单个文件到本地
hadoop fs -D fs.default.name=afs://tianqi.afs.com:9902 -D hadoop.job.ugi=username,password -get /app/ecom/native-ad-user/share/ernie_nsm_qt_eshop.tar.gz .

# -put: 把本地的单个文件上传到集群
hadoop fs -D fs.default.name=afs://wolong.afs.com:9902 -D hadoop.job.ugi=username,password -put xxx_file /user/sasd-goods/goods-search/xxy/mr_jobs/ugc/filter_qs_level/input

# -getmerge: 把服务器的多个文件合并后下载到本地
hadoop fs -D fs.default.name=afs://wolong.afs.com:9902 -D hadoop.job.ugi=username,password -getmerge /user/sasd-goods/goods-search/xxy/mr_jobs/ugc/filter_qs_level/output .

# -mkdir: 创建目录
hadoop fs -D fs.default.name=afs://tianqi.afs.com:9902 -D hadoop.job.ugi=username,password -mkdir /app/ecom/native-ad-user/share/

# -cp: 复制文件或目录(复制目录时不需要加-r)

MapReduce

  • 参数

    • 任务相关
      • -D num.key.fields.for.partition=1,用于分区的前n个字段
      • -D stream.num.map.output.key.fields=2,用于排序的前n个字段
      • -mapper “py/bin/python mapper.py”
      • -reducer “cat”
      • -file mapper.py
      • -file input_file
    • 配置相关
      • -D mapred.job.name=“search_development_xxx_goods_dev_offline”
  • 单文件submit.sh:只需指定mapper,reducer直接用cat指令

#!/usr/bin/env bash

INPUT_PATH="afs://wolong.afs.com:9902/user/sasd-goods/ccdb/output/ugc/xinghe_xxx/"

OUTPUT_DIR="afs://wolong.afs.com:9902/user/sasd-goods/goods-search/xxx/mr_jobs/ugc/"

hadoop fs -D hadoop.job.ugi=username,password -rmr ${OUTPUT_DIR}

# 这些参数都是基本的参数, 需要注意的是此处用了一个打包上传的py环境\
hadoop streaming \
        -D hadoop.job.ugi="username,password" \
        -D fs.default.name="afs://wolong.afs.com:9902" \
        -D mapred.job.tracker="yq01-heng-job.dmop.com:54311"\
        -D mapred.job.queue.name="goods" \
        -D mapred.job.name="search_development_xxx_goods_dev_offline" \
    -D mapred.job.map.capacity=2000 \
    -D mapred.job.reduce.capacity=2000 \
    -D mapred.map.tasks=1000 \
    -D mapred.job.priority=VERY_HIGH \
    -D abaci.split.optimize.enable=false \
    -D mapred.textoutputformat.ignoreseparator=true \
    -D mapred.max.map.failures.percent=2 \
    -D mapred.max.reduce.failures.percent=2 \
    -D stream.memory.limit=4000 \
    -D mapred.reduce.tasks=100 \
    -D num.key.fields.for.partition=1 \
    -D stream.num.map.output.key.fields=2 \
    -outputformat org.apache.hadoop.mapred.TextOutputFormat \
    -partitioner org.apache.hadoop.mapred.lib.KeyFieldBasedPartitioner \
    -cacheArchive "afs://wolong.afs.com:9902/user/sasd-goods/goods-search/lxxx05/python.tar.gz#py" \
    -input ${INPUT_PATH} \
    -output ${OUTPUT_DIR} \
    -mapper "py/bin/python mapper.py" \
    -reducer "cat" \
    -file mapper.py \
    -file input_file \
  • 单文件,mapper.py
	#!/usr/bin/python
	# -*- coding: utf-8 -*-
	
	# 单文件输入,直接print来输出结果
	import datetime
	import json
	import os
	import sys
	
	reload(sys)
	sys.setdefaultencoding('utf-8')
	
	
	def load_dict():
	    dic = set([])
	    
	    with open('input_file', 'r') as f:
	        for line in f:
	            dic.add(line.strip('\n'))
	    return dic
	
	
	if __name__ == "__main__":
	    dic = load_dict()
	
	    for line in sys.stdin:
	        line = line.strip('\n').split('\t')
	        
	        if len(line) != 2:
	            continue
	            
	        url, json_str = line[0], line[1]
	        if url in dic:
	            print('\t'.join([url, json_str]))
  • 双文件submit.sh:只需同时指定mapper、reducer
#!/usr/bin/env bash

INPUT_PATH=("afs://wolong.afs.com:9902/user/sasd-goods/goods-search/xxx/mr_jobs/ugc/filter_qs_level/input/" \
"afs://wolong.afs.com:9902/user/sasd-goods/ccdb/output/ugc/xinghe_xxx/")

OUTPUT_DIR="afs://wolong.afs.com:9902/user/sasd-goods/goods-search/xxx/mr_jobs/ugc/filter_qs_level/output/"

hadoop fs -D hadoop.job.ugi=xxx,yyy -rmr ${OUTPUT_DIR}

# 这些参数都是基本的参数, 需要注意的是此处用了一个打包上传的py环境\
hadoop streaming \
        -D hadoop.job.ugi="xxx,yyy" \
        -D fs.default.name="afs://wolong.afs.com:9902" \
        -D mapred.job.tracker="yq01-heng-job.dmop.com:54311"\
        -D mapred.job.queue.name="goods" \
        -D mapred.job.name="search_development_xxxx_goods_dev_offline" \
    -D mapred.job.map.capacity=2000 \
    -D mapred.job.reduce.capacity=2000 \
    -D mapred.map.tasks=1000 \
    -D mapred.job.priority=VERY_HIGH \
    -D abaci.split.optimize.enable=false \
    -D mapred.textoutputformat.ignoreseparator=true \
    -D mapred.max.map.failures.percent=2 \
    -D mapred.max.reduce.failures.percent=2 \
    -D stream.memory.limit=4000 \
    -D mapred.reduce.tasks=100 \
    -D num.key.fields.for.partition=1 \
    -D stream.num.map.output.key.fields=2 \
    -outputformat org.apache.hadoop.mapred.TextOutputFormat \
    -partitioner org.apache.hadoop.mapred.lib.KeyFieldBasedPartitioner \
    -cacheArchive "afs://wolong.afs.com:9902/user/sasd-goods/goods-search/lxxx05/python.tar.gz#py" \
    -input ${INPUT_PATH[@]} \
    -output ${OUTPUT_DIR} \
    -mapper "py/bin/python mapper.py" \
    -reducer "py/bin/python reducer.py" \
    -file mapper.py \
    -file reducer.py \
  • 双文件,mapper.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime
import json
import os
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

def data_parse_1():
    for line in sys.stdin:
        line = line.strip('\n').split('\t')
        print(len(line))
        if len(line) != 1:
            continue
        url = line[0]
        print('\t'.join([url, '0']))


def data_parse_2():
    for line in sys.stdin:
        line = line.strip('\n').split('\t')
        if len(line) != 2:
            continue
        url, json_str = line[0], line[1]
        print('\t'.join([url, '1', json_str]))

if __name__ == "__main__":
    filepath = os.environ.get('map_input_file', 'test/ps_oneday_log_click/20210823/part')
    path = filepath.split('/')[-2]

    if path == 'input':
        data_parse_1()
    elif path == 'xinghe_xxx':
        data_parse_2()
  • 双文件,reducer.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime
import json
import os
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

def main():
    dic = {}

    for line in sys.stdin:
        line = line.strip('\n').split('\t')
                
        if len(line) != 2 and len(line) != 3:
            continue

        if line[1] == '0':
            dic[line[0]] = "null"
        else:
            f_cls = dic.get(line[0], '-2')
            if f_cls != '-2':
                print('\t'.join([line[0], line[2]]))

if __name__ == "__main__":
    main()

MySQL

### 进入mysql客户端之前
# 获取系统生成的临时密码
grep 'temporary password' /var/log/mysqld.log 
# 使用root账户登录mysql(回车后**手动**输入上面的密码)
mysql -uroot -p

### 进入mysql客户端之后
# 第一次设置的root密码
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'Abc_1024_Root';

# 修改更简单的密码规则
mysql> set global validate_password.policy=0;
mysql> set global validate_password.length=1;

# 修改密码
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'aaabbbccc';
  • 基础用法
if(aaa = 'click' and bbb % 3600, 1, 0) as flag,
if(aaa = 'click' and bbb in (2, 4, 7) and ccc > 0, 'A', 'B') as flag2,
2 as flag3,
if(((cast(bhv_ts as BIGINT) div 1000 - 1711728000) % 3600) < 1800, 'A', 'B') as exp_group,

date_format(pay_time, 'yyyyMMdd') as event_day, 
(to_unix_timestamp(pay_time) - 1711728000) div 3600 as time_range,
date_format(from_unixtime(t1.ts_begin), 'yyyyMMdd') as event_day

count(1) as pv,
count(distinct t2.uid) as uv,
sum(buy_flag) as buy_pv, 
count(distinct if(gid_show_flag > 0, cuid, NULL)) as gid_show_uv, 

DATE_FORMAT(from_unixtime(q_time), '%Y-%m-%d') as q_date, anchor_id,
count(distinct t1.room_id) as room_id_cnt, 
count(distinct t1.anchor_uid) as anchor_uid_cnt, 
count(distinct if(user_type=1, t1.anchor_uid, NULL)) as anchor_cnt_with_real_question, 
sum(if(user_type=1, 1, 0)) as question_cnt, 
sum(if(user_type=1 and relay_type<>'', 1, 0)) as relay_cnt, 
sum(if(user_type=1 and relay_type<>'', 1, 0)) / sum(if(user_type=1, 1, 0)) as relay_percent

-- 这里的round(x, 4)保留4位小数(如果省略第2个参数,则四舍五入到最接近的整数)
cast(round(a_time / 1000, 4) as BIGINT) as a_time_2

where event_day between '20240426' and '20240505'
and live_type = 'liveshow'
and live_shop_type IN (2, 3)
and room_id is not null

group by aaa, bbb

order by rn desc
limit 5000

-- union会去重(因此效率会比union all低),union all返回所有数据
-- 注意:列的顺序、列数和类型需要对齐
union
union all
  • mysql终端
-- 数据库
show databases;
use xxx_database;

-- 数据表
desc xxx_table;
show tables;

-- \G: 拆分显示
select xxx from yyy limit 3 \G;

Redis

# 在CentOS7中安装redis
yum install redis

# 启动Redis服务
[sudo] service redis start

# 关闭Redis服务
[sudo] service redis stop

# 查看Redis服务状态
service redis status

IDE

  • Vscode
    • 插件
      • 语法高亮
        • Python:Pylint、Pylance
      • 查看历史提交人
        • Gitlens、Git History
      • 图标
        • Material Icon Theme

shell脚本

#!/bin/bash

# 指定输入文件和输出文件
input_file="product_id.txt"
output_file="results.txt"

# 读取文件中的URL并循环请求
# cat "$input_file" | head -n 100 | while read -r pid
cat "$input_file" | while read -r pid
do
    # 发送HTTP请求并获取结果
    result=$(curl --location 'http://pa-api.baidu-int.com/pic-polaris/ToolService' \
--header 'Content-Type: application/baidu.json-rpc' \
--data '{
"jsonrpc": "2.0",
"id": 1,
"method": "getCertainProductColumnsByIds",
"params": [
{
"productIds": ['$pid'],
"columns":["p0", "attr", "op"],
"orderType":"BY_COLUMN",
"maxVersion":1
}
]
}')

    # 将结果写入输出文件
    echo "$result" >> "$output_file"
done

echo "请求完成!结果已写入 $output_file"

时间

修改时区

# ubuntu,参考:https://cloud.tencent.com/developer/article/1721457

# step1 使用tzselect来获取国内的时间
tzselect
# 注:若tzselect命令出错,则先安装tzdata
apt-get install tzdata

# 更新本地时区文件
[sudo] cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

GPU

# 查看cuda版本
nvcc -V

# 查看cudnn版本、cuda版本(Ubuntu系统)
dpkg -l | grep libcudnn

Docker

  • 基础教程
# 安装docker
[sudo] curl https://get.docker.com/ | sh
  • docker信息
docker info

docker -v
  • 登录docker账户
# 登录xxx.com的账户(虽然也可以加上密码,但这不是安全操作:--password xxx)
docker login registry.cn-zhangjiakou.aliyuncs.com/xxx_user/test_docker --username xxx.com
  • 查看镜像、容器
# 查看镜像
docker images

# 查看正在运行的容器
docker ps
# 查看所有容器
docker ps -a
  • 拉取镜像
docker pull registry.cn-shanghai.aliyuncs.com/tcc-public/python:3
  • 运行容器
# i表示交互,t表示终端形式,bash表示使用的执行器
docker run -it registry.cn-shanghai.aliyuncs.com/tcc-public/python:3 bash
# i表示交互,t表示终端形式,d表示后台运行,/bin/bash表示使用的执行器
docker run -itd registry.cn-shanghai.aliyuncs.com/tcc-public/python:3 /bin/bash

# 执行后台的容器
docker exec -it be5ff11137cd /bin/bash
  • 镜像打标
docker tag 4033c56c11f3 torch2.4
  • 镜像保存(提交)
# 把xxx镜像提交到xxx账户中(需要先登录账户)
docker commit be5ff11137cd registry.cn-zhangjiakou.aliyuncs.com/xxx_user/demo:baseline
  • 构建 + 推送镜像
# 第一步:先拉取一个基础镜像
docker pull xxx

# 第二步:修改镜像后,保存镜像(需要先登录账户)
docker commit be5ff11137cd registry.cn-zhangjiakou.aliyuncs.com/xxx_user/demo:baseline

# 第三步:通过Dockerfile的方式,则需要写好Dockerfile,比如:传输文件、安装依赖、指定工作目录等(见下示例)

# 第四步:构建镜像
# --platform linux/amd64为可选操作:这是在mac系统上对镜像做了修改后,再构建的linux系统镜像
# -t是指定推送的位置,-f为Dockerfile的位置(若不指定,则默认是当前目录下名为Dockerfile的文件)
docker build --platform linux/amd64 -t registry.cn-zhangjiakou.aliyuncs.com/xxx_user/demo:v3 .
# 默认情况
docker build -t registry.cn-zhangjiakou.aliyuncs.com/xxx_user/demo:v3 .

# 第五步:推送镜像到指定仓库(需要先登录账户)
docker push registry.cn-zhangjiakou.aliyuncs.com/xxx_user/demo:v3
  • Dockerfile示例(该目录下有Dockerfile、LLaMA-Factory、run.sh3个文件或目录)
## 从天池基础镜像构建(from的base img 根据自己的需要更换,建议使用天池open list镜像链接:https://tianchi.aliyun.com/forum/postDetail?postId=67720)
FROM registry.cn-zhangjiakou.aliyuncs.com/xxx_user/demo:v3

##安装python依赖包
#RUN pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

## 把当前文件夹里的文件构建到镜像的根目录下,并设置为默认工作目录
RUN mkdir -p /app/LLaMA-Factory
ADD LLaMA-Factory /app/LLaMA-Factory
ADD run.sh /app
WORKDIR /app

## 镜像启动后统一执行 sh run.sh
CMD ["sh", "run.sh"]
  • 停止、删除镜像
# step1:找到该镜像所有的容器(假设只有1个容器,容器ID:0a7b22bffda4)
docker ps -a
# step2:先停止该镜像下所有的容器(容器ID:0a7b22bffda4)
docker stop 0a7b22bffda4
# step3:再删除该镜像下所有的容器
docker rm 0a7b22bffda4
# step4:最后删除该镜像(镜像ID:77831004a07e)
docker rmi 77831004a07e
  • 文件传输
# 本地文件cp进docker镜像
cp code_review/LLaMA-Factory 7af15ed15e7d:/new_tt
  • Mac上遇到docker客户端一直转圈打不开的问题:解决方式
    1. 关闭docker客户端
    2. 然后在系统其他目录里找到活动监视器这个软件,然后搜索docker,然后强制关闭所有相关的进程
    3. 在终端里进入cd ~/Library/Containers中,删除相关文件rm -rf com.docker.docker
    4. 重新打开docker客户端
  • bug
    • 当执行sudo service docker start开启docker服务时遇到以下的问题:
      • /etc/init.d/docker: line 62: ulimit: open files: cannot modify limit: Invalid argument
      • 解决方法:https://forums.docker.com/t/etc-init-d-docker-62-ulimit-error-setting-limit-invalid-argument-problem/139424
      • 具体来说:对/etc/init.d/docker文件的62行进行修改,把ulimit -Hn 524288改成ulimit -n 524288
      • 方法二:或者改变文件的权限好像也可以?sudo chown -R $USER /etc/init.d/docker

Kaggle

pip install kaggle
  • 基本命令
# 查看比赛
kaggle competitions list


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值