How to get a substring after the last underscore (_) in unix shell script

后端 未结 3 1069
醉话见心
醉话见心 2021-01-19 18:00

I have a String like this

this_is_test_string1_22
this_is_also_test_string12_6

I wanted to split and extracts string around the last unders

3条回答
  •  清酒与你
    2021-01-19 18:24

    So puting ideas from anubhava and glenn... Full Shell script can be... as follwoing. you can choose to output to a file or display on the commandline...

    #!/bin/ksh
    
    #FILE=/paht/to/file.txt or you can pass argument FILE=$1
    
     FILE=$1
     counter=`wc -l $FILE |cut  -d " " -f1`
    
    x=1
    
    while [ $x -le $counter ]
        do
                REC=`sed -n ${x}p $FILE`
    
                echo " ${REC%_*} and ${REC##*_} " >> output.txt
    
        let x=$x+1
    done
    

提交回复
热议问题