Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a string like that:


And i want to get a new string called in someway (like string2) with the original string without the two | at the start and at the end of it

so that i will have this


is that possible in bash?

share|improve this question
up vote 53 down vote accepted

You can do

echo $string2

Or if your string length is constant, you can do

echo $string2

Also, this should work

echo "|abcdefg|" | cut -d "|" -f 2

Also this

echo "|abcdefg|" | sed 's/^|\(.*\)|$/\1/'
share|improve this answer
and also awk -F\| '{ print $2 }' <<<"|string|" – enzotib Dec 23 '11 at 17:45
@enzotib You always have cool awk solutions. I need to learn awk. – Kris Harper Dec 23 '11 at 18:36
and also IFS='|' read string2 <<< $string :) – arrange Dec 23 '11 at 20:38
and also, in bash 4.2 and newer, "${string:1:-1}" – geirha Jul 5 '12 at 12:52
Read under the "parameter expansion" section in man bash. – Abhay Rana Sep 5 '12 at 20:44

Here's a solution that is independent of the length of the string (bash):

echo "${string:1:${#string}-2}"
share|improve this answer

Going off a few posts listed here it seems the simplest way to do it is:

echo ${string:1:-1}

edit: works on ubuntu with bash 4.2; does not work on centOS with bash 4.1

share|improve this answer

And another one:

echo "${string//|/}"
share|improve this answer

You can also use sed to remove the | not just referencing the symbol itself but using positional references as in:

$ echo "|abcdefg|" | sed 's:^.\(.*\).$:\1:'

Where ':' are the delimiters (you can replace them with / or any character not in the query, any sign following the s will do it) Here ^ (caret) means at the beginning of the input string and $ (dollar) means at the end. The . (point) that it's after the caret and the one that it's before the dollar sign represents a single character. So in other words we are deleting the first and last characters. Take in mind this will delete any characters even if | it's not present in the string.


$ echo "abcdefg" | sed 's:^.\(.*\).$:\1:'
share|improve this answer

Another way with head & tail:

echo -n "|abcdefg|" | tail -c +2 | head -c -1


share|improve this answer
I had a string of [something something] with a goal to cut brackets, so echo "[something something]" | tail -c +2 | head -c -2 worked out. Thanks for a tip! – Ain Tohvri Dec 13 '15 at 15:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.