How to delete the main section in bash

How to remove part of a line to a certain character?

Example.) If I have the line testFile.txt.1 and testFile.txt.12345 , how can I delete 1 and 12345 ?

EDIT: I wanted to delete and throw away the first part of the line to a specific character and save it.

+7
string bash
source share
5 answers

using only bash objects

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

to delete before zero

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

Another method, you can split your string using IFS

 $ s=testFile.txt.12345 $ IFS="." $ set -- $s $ echo $1 testFile $ echo $2 txt $ echo $3 12345 
+11
source share

If you just want to remove the known suffix from the file name, you can use basename :

 basename testFile.txt.1 .1 basename testFile.txt.12345 .12345 
+1
source share

You can use sed to search and replace. The <<< operator will pass the string to stdin.

 $ sed 's/\.[0-9]*$//' <<< "testFile.txt.1" testFile.txt $ sed 's/\.[0-9]*$//' <<< "testFile.txt.12345" testFile.txt 
+1
source share

The question is a bit unclear - the above example may mean that you want to delete all #s or delete the part after the last "." or delete the part after the first "1" or even delete all characters after the symbol 13. Please clarify.

If you want to delete the first N characters in the string (for example, "before character number 13"), do echo testFile.txt.1 | cut -c14- echo testFile.txt.1 | cut -c14- . On the other hand, to save characters 1-13, do echo testFile.txt.1 | cut -c1-13 echo testFile.txt.1 | cut -c1-13

If you mean that you want to delete the initial characters before the first occurrence of a certain character (in your example, which seems to be โ€œ1โ€), do echo testFile.txt.1 | perl -e 's/^[^1]*//;' echo testFile.txt.1 | perl -e 's/^[^1]*//;' . To delete everything AFTER the first "1", do echo testFile.txt.1 | perl -e 's/1.*$//;' echo testFile.txt.1 | perl -e 's/1.*$//;'

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

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

0
source share
 # 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:]]*}"}" 
0
source share

All Articles