sed 命令匹配行操作

#查看匹配到行的前面一行

cat  file.txt  |grep '5' -B1


#查看匹配到行的后面两行

cat  file.txt  |grep '5' -A2


#查看匹配到行的前后各两行

cat  file.txt  |grep '5' -C2



#查看两个字符串之间的内容(在一行中才有效)

cat file.txt
<python>123456789</python>

cat file.txt | grep -E "<python>.*</python>" | awk '{t=$0;gsub(/.*<python>|</python>.*/,"",t);print t}' > new_file.txt

cat new_file.txt
123456789



#查看两个字符串之间的内容(在多行中有效)

cat file.txt
begin ok start
1,2
4
67
stop end ok

#想要 begin ok 到 end ok 之间的内容
#!/bin/sh
begin_num=`cat -n  file.txt|grep -rin 'begin ok' file.txt|awk -F : '{print $1}'`
begin_string=`cat -n  file.txt|grep -rin 'begin ok' file.txt|awk -F : '{print $2}'`
begin_add1_num=$(($begin_num+1))
end_num=`cat -n  file.txt|grep -rin 'end ok' file.txt|awk -F : '{print $1}'`
end_string=`cat -n  file.txt|grep -rin 'end ok' file.txt|awk -F : '{print $2}'`
end_add1_num=$(($end_num-1))
#从左向右截取第一个 begin ok 后的字符串
echo ${begin_string#*begin ok}   
sed -n "${begin_add1_num},${end_add1_num}p" file.txt
#从右向左截取 第一个 / 后的字符串
echo ${end_string%end ok*}

结果:

start
1,2
4
67
stop

#删除文件中的一段内容

#!/bin/sh
while read line
 do
  echo "${line}"
  #指定行号
  para_num=`grep -rin "${line}" file.txt|awk -F ":" '{print $1}'`
  echo "参数指定行:${para_num}"
  para_up_num=$((${para_num}-2))
  para_dow_num=$((${para_num}+2))
  echo ${para_up_num} ${para_dow_num}
  sed -i "${para_up_num},${para_dow_num}d" file.txt
 done  < config.conf
 
echo "所有表处理完成"
#说明:配置文件config.conf中尽量唯一,在文件中只能配置一行

#修改文件中的指定一行内容


#!/bin/sh
while read line
 do
  echo "${line}"
  para_old=`grep -ri "${line}" file.txt`
  #指定行号
  para_num=`grep -rin "${line}" file.txt|awk -F ":" '{print $1}'`
  echo "参数指定行:${para_num}"
  echo "替换之前的参数值:${para_old}"
  para_1="<para>"
  para_2="$(bizDate) 1 "SUBSTR(DEFAULT_DT,1,4)||SUBSTR(DEFAULT_DT,6,2)||SUBSTR(DEFAULT_DT,9,2)" null $(bizDate)</para>"
  para_new="${para_1}${line} ${para_2}"
  sed -i "${para_num}c ${para_new}" file.txt
  echo "替换之后的参数值:${para_new}"
 done  < config.conf
 
echo "所有表处理完成"

#说明:配置文件config.conf中尽量唯一,在文件中只能配置一行,其中para_1para_2 是这一行的内容
原文地址:https://www.cnblogs.com/hello-wei/p/12721930.html