shell小技巧(六)读取文件末尾为数字行的末尾数字

以上一题文件s1.txt为源文件
方法1:
awk -F "[^0-9]" '/[0-9]$/{print $NF}'  s1.txt

awk -v FS="[^0-9]" '/[0-9]$/{print $NF}' 
设置分隔符为非数字,对以数字结尾的行输出最后1个字段

方法2:
sed -nr '/[0-9]$/{s/.*[^0-9]([0-9]+)$/\1/;p}' 

sed -n /[0-9]$/p s1.txt | sed -nr 's/.*[^0-9]([0-9]+)$/\1/g;p'
第一种写法是用了嵌套
方法3:
使用read line循环实现。

此方法不如其他两种方法简洁。主要是想练习几个知识点。

包括:文件存在判断、逐行读取、获取字符串长度、判断是否是数字、终止当前循环和终止本次循环、获取部分字符串

#!/bin/bash

> s4.txt

if [ -f s1.txt ]; then

   echo "starting..."

else

   echo "error!need s1.txt!"

   exit 1

fi

f1=""

f0="" 

f2=0

#echo $f0

#exit 0

while read line

do

 f0=`echo $line | sed -n '/[0-9]$/p'`

 f1=`echo $f0 | awk '{print length($0)}'`

#echo $f1

 if [ $f1 -eq 0 ]; then

   f1=0

   echo "this line is 0"

   continue;

 fi

#echo "this line is gt 0 ------$f1"

   f2="" 

   j=0

   while [ $j -le $f1 ];  

    do

      f2=${line:j}

      echo $f2 | grep -q '[^0-9]'

      f3=$?

      if [ $f3 -ge 1 ]; then

         #this is number,output

         echo $f2 >>s4.txt

         echo $f2

        break;

      fi

      let j=j+1

    done

   f0=""

done < s1.txt

发布了53 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/bigwood99/article/details/105014268