Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to removing leading section in bash

Tags:

string

bash

How can I remove parts of a string up to a certain character?

Ex.) If I have the string testFile.txt.1 and testFile.txt.12345 how can I remove the 1 and 12345?

EDIT: I meant to remove and throw away the first part of a string up to a certain character and keep the end of it.

like image 838
Kyle Van Koevering Avatar asked Apr 21 '10 04:04

Kyle Van Koevering


People also ask

How do I remove the first part of a string in bash?

Using the parameter expansion syntax To remove the first and last character of a string, we can use the parameter expansion syntax ${str:1:-1} in the bash shell. 1 represents the second character index (included). -1 represents the last character index (excluded).

How do I remove leading zeros in bash?

As $machinenumber that is used has to have a leading zero in it for other purposes, the idea is simply to create a new variable ( $nozero ) based on $machinenumber , where leading zeros are stripped away. $machinetype is 74 for now and hasn't caused any problems before.

How to cut from string in bash?

Using the cut Command You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.

How do I remove a character from a string in bash?

The tr command (short for translate) is used to translate, squeeze, and delete characters from a string. You can also use tr to remove characters from a string. For demonstration purposes, we will use a sample string and then pipe it to the tr command.


1 Answers

using just bash facilities

$ s=testFile.txt.1
$ echo ${s%.*}
testFile.txt

$ s=testFile.txt.12345
$ echo ${s%.*}
testFile.txt

to remove before leading zero

$ echo ${s#*.}
txt.12345

Other method, you can split your string up using IFS

$ s=testFile.txt.12345
$ IFS="."
$ set -- $s
$ echo $1
testFile
$ echo $2
txt
$ echo $3
12345
like image 143
ghostdog74 Avatar answered Nov 04 '22 21:11

ghostdog74