How to remove the first 5 characters from a string?

  • Follow


For example, the string is: myStr1122334455. Remove "myStr" and the
string becomes: 1122334455.

Thanks.
0
Reply junw2000 (221) 5/26/2010 6:17:35 AM

On 2010-05-26, Jack wrote:
> For example, the string is: myStr1122334455. Remove "myStr" and the
> string becomes: 1122334455.

string=myStr1122334455

    In any standard Unix shell:

newstring=${string#?????}

    In bash or ksh93:

newstring=${string:5}


-- 
   Chris F.A. Johnson, author           <http://shell.cfajohnson.com/>
   ===================================================================
   Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
   Pro Bash Programming: Scripting the GNU/Linux Shell (2009, Apress)
   ===== My code in this post, if any, assumes the POSIX locale  =====
   ===== and is released under the GNU General Public Licence    =====
0
Reply Chris 5/26/2010 6:33:11 AM


Jack  <junw2000@gmail.com> wrote:
>For example, the string is: myStr1122334455. Remove "myStr" and the
>string becomes: 1122334455.

Jack -

Depending on how long your string could use 'cut -c' and specify a 
series of characters that you wish to cut.

$ echo myStr1122334455 | cut -c6-15
1122334455
-- 
..sdf.org!martians
SDF Public Access UNIX System, Est. 1987 - http://sdf.org
0
Reply martians 5/26/2010 6:40:59 AM

2010-05-25, 23:17(-07), Jack:
> For example, the string is: myStr1122334455. Remove "myStr" and the
> string becomes: 1122334455.
[...]

POSIX:

str1=myStr1122334455
str2=${str1#?????}

(if there are fewer characters than 5, none are removed).

zsh:

str2=$str1[6,-1]

ksh93, bash:

str2=${str1:5]

any Bourne compatible:

str2=`expr "x$str1" : 'x.\{5\}\(.*\)'`
or for even greater portability:
str2=`expr "x$str1" : 'x.....\(.*\)'`

(in all those, fewer than 5 characters are removed).

In the expr ones, the exit status will be non-zero if there are
fewer than 5 characters or if $str2 becomes 0 or -0 or 000...

-- 
Stéphane
0
Reply Stephane 5/26/2010 6:47:59 AM

2010-05-26, 06:40(+00), Stephen Jones:
> Jack  <junw2000@gmail.com> wrote:
>>For example, the string is: myStr1122334455. Remove "myStr" and the
>>string becomes: 1122334455.
[...]
> Depending on how long your string could use 'cut -c' and specify a 
> series of characters that you wish to cut.
>
> $ echo myStr1122334455 | cut -c6-15
> 1122334455

Note that in case the string contains newline characters, it
removes up to the first 5 characters of each line in the string.

Also note that echo may do some transformations on the string it
is passed (for instance if it starts with "-" or contains "\"
characters). printf should be prefered.

printf '%s\n' "$string" | dd ibs=5 skip=1 2> /dev/null

Also note you can use cut -c6- to cut from the 6th character to
the end of the line.

-- 
Stéphane
0
Reply Stephane 5/26/2010 10:13:13 AM

4 Replies
8306 Views

(page loaded in 0.11 seconds)

Similiar Articles:













7/19/2012 3:27:29 PM


Reply: