Shell-script - String manipulation cut last 10 character, Cut first or Last ten characters

String manipulation cut last 10 character

How to cut first and last x characters of each line from a file?

Before strating lets assume that we have a file course.txt, In this file we have alphabets and numeric digits. Lets have our goal set to extarct or parse the alphabets and numbers in to different variables. This can be done using different methods, here we can work with a simple work around to manipulate the strings.

# cat names.txt

Computer Science 45321212
Electronic & communication 90871243
Mechanical Engineering 12354323
Civil Engineering 98765321
External Engineers 23415690


In this shell script first we will try to find the string length of each line, then we will try to find out string length, extract the Numeric values then extract only the alphabets or departments from the file course.txt
# vi string-manipulate.sh

#! /bin/bash

while read line
do
 #Find String Length
 length=${#line}
 echo "SringLength = $length"

 # Cut last 8 numeric values
 echo "Numbers = "${line:(-8)}

 # Cut all other Alphabets
 length=$(expr $length - 9)
 echo "Deps = "${line:0:($length)}
 echo "------------------------------"

done<course.txt


Output:
SringLength = 25
Numbers = 45321212
Deps = Computer Science
------------------------------
SringLength = 39
Numbers = 90871243
Deps = Electronic & communication Eng
------------------------------
SringLength = 31
Numbers = 12354323
Deps = Mechanical Engineering
------------------------------
SringLength = 26
Numbers = 98765321
Deps = Civil Engineering
------------------------------
SringLength = 27
Numbers = 23415690
Deps = External Engineers
------------------------------

Another way to find the length of the string is
 length=$(echo $line | wc -c)
Use the above line to find the length of the string instead of "length=${#line}". Shell scripting also do have some string manipulation functions as in C programming.

The topic on Shell-script - String manipulation cut last 10 character is posted by - Math

Hope you have enjoyed, Shell-script - String manipulation cut last 10 characterThanks for your time

Tech Bluff