Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a string like that:

|abcdefg|

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

abcdefg

is that possible in bash?

share|improve this question

6 Answers 6

up vote 33 down vote accepted

You can do

string="|abcdefg|"
string2=${string#"|"}
string2=${string2%"|"}
echo $string2

Or if your string length is constant, you can do

string="|abcdefg|"
string2=${string:1:7}
echo $string2

Also, this should work

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

Also this

echo "|abcdefg|" | sed 's/^|\(.*\)|$/\1/'
share|improve this answer
2  
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
1  
and also IFS='|' read string2 <<< $string :) –  arrange Dec 23 '11 at 20:38
3  
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. –  Capt.Nemo Sep 5 '12 at 20:44

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

string="|abcdefg|"
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:

string="|abcdefg|"
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

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:'
abcdefg

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.

EX:

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

And another one:

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

Another way with head & tail:

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

abcdefg

share|improve this answer

Your Answer

 
discard

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.