user3708408
user3708408

Reputation: 59

truncate a string in bash

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

Answers (3)

DiegoB
DiegoB

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

John1024
John1024

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.

Example

$ s=00001_99_AA_FLLLA
$ x=_${s#*_*_}; s=${s%$x}
$ echo "$s"
00001_99

How it works

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:

  1. 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
  1. 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

choroba
choroba

Reputation: 241828

Use parameter expansion:

while [[ $string = *_*_* ]] ; do
    string=${string%_*}
done
  • ${string%_*} removes the last _ and whatever follows it from $string
  • we do it while $string contains at least two underscores

Upvotes: 2

Related Questions