How to removing leading section in bash
How can I remove parts of a string up to a certain character?
Ex.) If I have the string testFi开发者_开发问答le.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.
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
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
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
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/\.[^.]+/./;'
# 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:]]*}"}"
精彩评论