4

For example, I have a string, " some string", and I want to put "some string" in another string variable. How do I do that?

My code:

function get_title() {
    t1=$(get_type "$1")
    t2="ACM Transactions"
    t3="ELSEVIER"
    t4="IEEE Transactions"
    t5="MIT Press"
    if [ "$t1"=="$t2" ];
        then
        title=$(less "$1" | head -1)
    elif [ "$t1"=="$t5" ];
    then
        title=$(less "$1" | head -3)
    fi
    echo "$title"
}

As you can see the $title can return unwanted whitespace in front of text in center aligned texts. I want to prevent that.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shawon0418
  • 181
  • 1
  • 3
  • 12
  • Specifically, take a look at the third code block of the [top-rated answer](http://stackoverflow.com/a/3232433/2489497) ("How to remove leading whitespace only") – Caleb Brinkman Sep 24 '15 at 04:05
  • Oh, thanks. I didn't check at that question because I didn't want to trim whitespace completely. @CalebBrinkman – Shawon0418 Sep 24 '15 at 04:07

1 Answers1

15

A robust and straightforward approach is to use sed e.g.

$ sed 's/^[[:space:]]*//' <<< "$var"

If you are willing to turn on extended globbing (shopt -s extglob), then the following will remove initial whitespace from $var:

 "${var##+([[:space:]])}"

Example:

var=$' \t abc \t ' echo "=${var##+([[:space:]])}="
=abc   =
peak
  • 105,803
  • 17
  • 152
  • 177
  • 2
    You can also use a capture group in a regular expression to avoid starting a new process for `sed`: `[[ $var =~ [[:space:]]*(.*) ]] && var=${BASH_REMATCH[1]}` – chepner Sep 24 '15 at 12:08