#View the line before the matched line
cat file.txt |grep '5' -B1
#View the next two lines that match the line
cat file.txt |grep '5' -A2
#View two lines before and after the matched line
cat file.txt |grep '5' -C2
#View the content between two strings (only valid in one line)
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
#View the content between two strings (valid in multiple lines)
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 )) #Cut the string after the first begin ok from left to right echo $ {begin_string # * begin ok} sed -n " $ {begin_add1_num}, $ {end_add1_num} p " file .txt #From right to left Intercept the first / after string echo $ {end_string% end ok *}
result:
start 1,2 4 67 stop
#Delete a piece of content in the file
#!/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 " all tables are processed " #Description : Try to be unique in the configuration file config.conf, only one line can be configured in the file
#Modify a specified line of content in the file
#! / bin / sh while read line do echo " $ {line} " para_old = ` grep -ri " $ {line} " file .txt` #Specify the line number para_num =` grep -rin " $ {line} " file .txt | awk -F " : " ' {print $ 1} ' ` echo " Parameter specification line: $ {para_num} " echo " The parameter value before replacement: $ {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 " The parameter value after replacement: $ {para_new} " done < config.conf echo " All tables are processed " #Description : Try to be as unique as possible in the configuration file config.conf. Only one line can be configured in the file, where para_1 and para_2 are the contents of this line