Reputation: 59
I have a string like this in bash: *_*_*_*
where * could be any number of letters, numbers, and legal characters.
I need to truncate the string to *_*
.
An example is: 00001_99_AA_FLLLA -----> 00001_99
How can I do this in bash?
Upvotes: 2
Views: 6525
Reputation: 1
If the strings you want to truncate are in a file called myfile.txt
, in bash, you can always do:
cut -d_ -f1,2 myfile.txt
The first option -d_
will specify the underscore as the delimiting character, and the second option -f1,2
specifies that you want fields 1 and 2 (only) returned.
So, you could write the output to another file like this:
cut -d_ -f1,2 myfile.txt > output.txt
Upvotes: 0
Reputation: 113834
If s
is your string, try:
x=_${s#*_*_}
s=${s%$x}
This approach has two advantages: (1) it requires no loops which should make it fast, and (2) it is POSIX and therefore portable to any POSIX-compatible shell.
$ s=00001_99_AA_FLLLA
$ x=_${s#*_*_}; s=${s%$x}
$ echo "$s"
00001_99
This code works in two steps: first we find the string that we want to remove from s
and then we remove it. In more detail:
x=_${s#*_*_}
This sets x
to the string that we want to remove from s
. ${s#*_*_}
removes from s
the shortest string that contains two underscores. _${s#*_*_}
puts an underscore in front of that
string. Using our example:
$ s=00001_99_AA_FLLLA; echo "_${s#*_*_}"
_AA_FLLLA
s=${s%$x}
This removes $x
from the end of string s
. This gives us what we are looking for. Using our example:
$ echo "${s%$x}"
00001_99
Upvotes: 2
Reputation: 241828
Use parameter expansion:
while [[ $string = *_*_* ]] ; do
string=${string%_*}
done
${string%_*}
removes the last _ and whatever follows it from $stringUpvotes: 2