5

Inside of a while read line loop, I see this variable expansion ${line/device name:}. I've tried running the script with my own input file and it just prints out the line.

Can you tell me what that expansion is doing?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Jimbo
  • 51
  • 1
  • Both answers are correct, but here's the documentation on parameter expansions for later reference and editing into answers: http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html – Jeff Bowman Sep 16 '15 at 22:52

2 Answers2

4

The variable name is line. / is for string substitution, that is "device name:" if exists anywhere in the $line is removed.

> line="a device name: some name"
> echo ${line/device name:}
a  some name

You may also see # and % substitutions, which stand for substitutions in the line begin and end. Also beware that such / substitution is a bash-specific feature (e.g. ash doesn't support it, % and # are seemingly portable), so you should use #!/bin/bash instead of #!/bin/sh as a hashbang in the beginning of your script.

chepner
  • 497,756
  • 71
  • 530
  • 681
user3159253
  • 16,836
  • 3
  • 30
  • 56
  • `%` and `#` are indeed portable, being [part of the POSIX shell specification](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02). – chepner Sep 16 '15 at 22:51
  • Thank you. Excellent answer! – Jimbo Sep 17 '15 at 16:52
3

It returns $line with the substring device name: removed. From the bash man page:

${parameter/pattern/string}
       Pattern substitution.  The pattern is expanded to produce a pattern just as in
       pathname  expansion.   Parameter  is expanded and the longest match of pattern
       against its value is replaced with string.  If  pattern  begins  with  /,  all
       matches of pattern are replaced with string.  Normally only the first match is
       replaced.  If pattern begins with #, it must match at  the  beginning  of  the
       expanded  value  of parameter.  If pattern begins with %, it must match at the
       end of the expanded value of parameter.  If string is null, matches of pattern
       are  deleted and the / following pattern may be omitted.  If parameter is @ or
       *, the substitution operation is applied to each positional parameter in turn,
       and  the  expansion  is the resultant list.  If parameter is an array variable
       subscripted with @ or *, the substitution operation is applied to each  member
       of the array in turn, and the expansion is the resultant list.
John Kugelman
  • 349,597
  • 67
  • 533
  • 578