views:

328

answers:

5

This is probably a really stupid question...but 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?

Thanks a lot for the help

EDIT: Sorry it was really unclear. I meant to remove and throw away the first part of a string up to a certain character and keep the end of it. My question has been answered in many different ways...Thanks everyone.

A: 

If you just want to remove a known suffix from a filename, you can use basename:

basename testFile.txt.1 .1
basename testFile.txt.12345 .12345
Michael Mrozek
Is there an elegant way to also remove that leading period in the same line?I can do it in two, I was just curious...Thanks a lot for your help!
Kyle Van Koevering
I'm not sure what leading period you're talking about
Michael Mrozek
+1  A: 

You could use sed to do a search and replace. The <<< operator will pass in a string on stdin.

$ sed 's/\.[0-9]*$//' <<< "testFile.txt.1"
testFile.txt
$ sed 's/\.[0-9]*$//' <<< "testFile.txt.12345"
testFile.txt
John Kugelman
+4  A: 

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
ghostdog74
A: 

The question is a bit unclear - the example provided may mean you want to remove all #s, or remove the part after the last ".", or remove the part after the first "1", or even remove all charcters after character 13. Please clarify.

If you mean that you want to remove first N characters in a string (e.g. "up to a character # 13"), do echo testFile.txt.1 | cut -c14-. To retain the chars 1-13, on the other hand, do echo testFile.txt.1 | cut -c1-13

If you mean that you want to remove the beginning characters until the first occurence of a specific character (in your example that seems to be "1"), do echo testFile.txt.1 | perl -e 's/^[^1]*//;'. To remove everything AFTER the first "1", do echo testFile.txt.1 | perl -e 's/1.*$//;'

If you want to remove all the #s, do echo testFile.txt.1 | perl -e 's/\d//g;' or without Perl, echo testFile.txt.1 | tr -d "[0-9]"

If you want to remove everything after the last ".", do echo testFile.txt.1 | perl -e 's/\.[^.]+/./;'

DVK
Why the down-vote?
DVK
A: 
# remove string prefix up to the first digit
var='testFile.txt.12345'
var='test1File.txt.12345'
var='testFile.txt.1'
var='testFile.txt'

echo "${var#"${var%%[[:digit:]]*}"}"
yabt