How to trim a string using linux bash script

This is pretty simply done using the sed command. All you have to know is regular expressions.

To remove leading white spaces

sed 's/^ *//g'

To remove trailing white spaces

sed 's/ *$//g'

So as an example,

$ echo "  aaaa   bbbb      " | sed 's/^ *//g' | sed 's/ *$//g'
aaaa   bbbb

Thats it.


Tags: , ,

11 Responses to “How to trim a string using linux bash script”

  1. Gleise Says:

    Thanks!! This helped me a lot.

  2. Eduardo Says:

    Best answer for this problem that I found.

  3. piet Says:

    Very nice. Thanks.

    I made next variant to remove both leading and trailing white spaces:

    sed ‘s/^ *//g;s/ *$//g;’ <<< " aaaa bbbb "

  4. pete Says:

    tr -d ‘ ‘
    remove all whitespace from a string:

    cat myfile | tr -d ‘ ‘

    Thanks Saminda, your post helped me get here:

  5. nikesh Says:

    remove the blan space from start: echo $var | sed -e ‘s/^\s+//’
    remove the blan space from end : echo $var | sed -e ‘s/\s+*$//’

  6. Nadhya Says:

    how to remove a particular string in a file? please help me out

  7. samindaw Says:

    Hi Nadhya,
    Try something like the following,
    $ cat your_file.txt | sed ‘s/string_to_remove//g’ > new_file.txt

  8. Virendra Dalvi Says:

    what would be the string to remove the blank spaces before a specific column.

    # cat test | awk ‘{for(i=4; i<=11; ++i) $i=FS; print $0}'
    2011-09-09 11:04:56.04 BST {showalert}

    I would like to remove the space before column $4 and then print the output like –
    2013-09-09 11:04:56.04 BST {showalert}


  9. Virendra Dalvi Says:

    Sorry I guess the spaces before SHOWALERT in the first command output got cut off.

  10. s Says:

    Piping cant be solution to this. because “sed” wont wait much for the first string to be available. You may get Broken Pipe error. in fact thats what i am getting. not sure what else i can try.

  11. Says:

    no, it’s not! you don’t need the ‘g’ at the end of regexp

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: