tags:

views:

539

answers:

4

for example qa_sharutils-2009-04-22-15-20-39, want chop last 20 bytes, and get 'qa_sharutils'.

I know how to do it in sed, but why $A=${A/.{20}$/} does not work?

Thanks!

+3  A: 

If your string is stored in a variable called $str, then this will get you give you the substring without the last 20 digits in bash

${str:0:${#str} - 20}

basically, string slicing can be done using

${[variableName]:[startIndex]:[length]}

and the length of a string is

${#[variableName]}

EDIT: solution using sed that works on files:

sed 's/.\{20\}$//' < inputFile
Charles Ma
A: 

In the ${parameter/pattern/string} syntax in bash, pattern is a path wildcard-style pattern, not a regular expression. In wildcard syntax a dot . is just a literal dot and curly braces are used to match a choice of options (like the pipe | in regular expressions), so that line will simply erase the literal string ".20".

John Kugelman
Thanks for your explanations, but seems only one answer can be accepted, sorry:)
chenz
A: 

There are several ways to accomplish the basic task.

$ str="qa_sharutils-2009-04-22-15-20-39"

If you want to strip the last 20 characters. This substring selection is zero based:

$ echo ${str::${#str}-20}
qa_sharutils

The "%" and "%%" to strip from the right hand side of the string. For instance, if you want the basename, minus anything that follows the first "-":

$ echo ${str%%-*}
qa_sharutils
semiuseless
A: 

only if your last 20 bytes is always date.

$ str="qa_sharutils-2009-04-22-15-20-39"
$ IFS="-"
$ set -- $str
$ echo $1
qa_sharutils
$ unset IFS

or when first dash and beyond are not needed.

$ echo ${str%%-*}
qa_sharutils
ghostdog74