Re: replacing substring starting with a % sign

From: laura fairhead (laura_fairhead_at_INVALID.com)
Date: 11/06/03


Date: Thu, 6 Nov 2003 01:38:46 +0000

In article <3b87395.0311051520.18702dc1@posting.google.com>,
Arvinder Singh wrote:
>I am trying to replace a substring "%n" with another value in a bash
>script.
>
>com=`echo ${comm//%n/ls}` doesnt seem to work. I tried escaping the %
>sign with a \ but that doesnt seem to work. I am new to this so any
>help would be appreciated.

You don't need the command substitution/echo since ${...//./} is
built-in to bash.

A '%' or '#' at the start of the pattern is special and makes the
rest of the pattern match the end or the start of the string respectively.
You might expect that quoting that character would protect it from
being interpretted (as '*' and '?' in the pattern behave this way)
however bash doesn't allow that. You could get around that problem
using a bracket expression;

comm=${comm//[%]n/ls}

The more portable way which works in any shell would be to use 'sed'
then you do need the command substitution;

comm=`echo "$comm" |sed 's/%n/ls/g'`

But this method has a few quirks because if $comm is "-n" or "-e"
it could be interpretted as an option by 'echo', if $comm contains
any backslash characters they may be interpretted by 'echo' and
if $comm has any trailing newlines they get deleted by the command
substitution itself. Most of the time those issues are not a problem
because you will know $comm can't contain such data thou' :)

byefornow
laura

-- 
echo alru_aafriehdab@ittnreen.tocm |sed 's/\(.\)\(.\)/\2\1/g'


Relevant Pages

  • Re: diff files matching a pattern
    ... The size really doesn't matter for those extra large files. ... # pattern must be in double quotes to avoid shell expasion ... echo $co files compared. ... To UNSUBSCRIBE, email to debian-user-REQUEST@xxxxxxxxxxxxxxxx ...
    (Debian-User)
  • Re: Funny that
    ... >> echo the pattern of those 3 Near Honshu, Japan and northerly on today's ...
    (sci.geo.earthquakes)
  • Re: case statement to validate input
    ... >I'm expecting input to be a char followed by up to 7 chars or digits. ... There is no closing bracket to delimit the case pattern but more ... *) echo "Correct Input";; ...
    (comp.unix.shell)
  • ksh problem with patern substitution
    ... I have the following problem with ksh using pattern substitution: ... I have the following simple script: ... echo OK ... echo notOK ...
    (comp.unix.shell)
  • Re: Removing days
    ... for day in `echo $a` ... What could I modify to get this script working good? ... Much prettier. ... man comm for details. ...
    (comp.unix.shell)