如何向sed命令传入shell 变量


在使用linux 进行自动化批量处理的时候经常会用到一个强大的命令,sed
根据这个命令人们可以很方便的对文件进行修改。
本文描述如何在批量化处理时传递shell 变量给sed。

准备

shell 变量

j=1000

需要修改的文件 “test.txt”

这是一个测试文件
N = 30
请使用sed 将第二行的30修改为1000

执行sed 语句

sed -i '2, 2s/30/'"$j"'/g' test.txt

命令解释

-i :直接修改文件
2,2s :匹配从第2行到第二行的内容
/ :分割符
30 :要匹配的字符
“$j” :引用shell变量
g :从行首匹配到行尾
text.txt :待修改文件

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
``` #!/bin/bash cpu_threshold=80 cpu_duration=60 mem_threshold=70 mem_duration=70 disk_threshold=90 disk_duration=90 interval=60 url="http://aaa.com" while true; do ip=$(hostname -I) # CPU usage cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{printf "%.1f\n", 100 - $1}') if (( $(echo "$cpu_usage > $cpu_threshold" | bc -l) )); then cpu_time=$((cpu_time + interval)) if (( $cpu_time > $cpu_duration )); then cpu_time=0 top_procs=$(ps -eo pid,user,%cpu,cmd --sort=-%cpu | head -n 4) data="{\"server_ip\":\"$ip\",\"resource_type\":\"cpu\",\"usage\":\"$cpu_usage\",\"duration\":\"$cpu_duration\",\"top_procs\":\"$top_procs\"}" curl -H "Content-Type: application/json" -X POST -d "$data" "$url" fi else cpu_time=0 fi # Memory usage mem_usage=$(free | awk '/Mem/ {printf "%.1f\n", $3/$2 * 100.0}') if (( $(echo "$mem_usage > $mem_threshold" | bc -l) )); then mem_time=$((mem_time + interval)) if (( $mem_time > $mem_duration )); then mem_time=0 top_procs=$(ps -eo pid,user,%mem,cmd --sort=-%mem | head -n 4) data="{\"server_ip\":\"$ip\",\"resource_type\":\"memory\",\"usage\":\"$mem_usage\",\"duration\":\"$mem_duration\",\"top_procs\":\"$top_procs\"}" curl -H "Content-Type: application/json" -X POST -d "$data" "$url" fi else mem_time=0 fi # Disk usage disk_usage=$(df -h | awk '$NF=="/"{printf "%s\n", $5}') disk_usage=${disk_usage%?} if (( $(echo "$disk_usage > $disk_threshold" | bc -l) )); then disk_time=$((disk_time + interval)) if (( $disk_time > $disk_duration )); then disk_time=0 top_files=$(du -ah / | sort -nr | head -n 3) data="{\"server_ip\":\"$ip\",\"resource_type\":\"disk\",\"usage\":\"$disk_usage\",\"duration\":\"$disk_duration\",\"top_files\":\"$top_files\"}" curl -H "Content-Type: application/json" -X POST -d "$data" "$url" fi else disk_
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值