Extracting Parts of String "#" vs "%"


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers Extracting Parts of String "#" vs "%"
# 1  
Old 09-05-2015
Extracting Parts of String "#" vs "%"

Hello,

I have a question regarding extracting parts of a string and the meaning of # and % in the syntax. I created an example below.

Code:
[root@localhost scriptspractice]# filename=/first/second/third/fourth
[root@localhost scriptspractice]# 
[root@localhost scriptspractice]# echo $filename
/first/second/third/fourth
[root@localhost scriptspractice]# 
[root@localhost scriptspractice]# echo "${filename##*/}"
fourth
[root@localhost scriptspractice]# 
[root@localhost scriptspractice]# echo "${filename%/*}"
/first/second/third

In both of these examples , I wanted to: extract only the fourth part of the string and extract everything but the fourth part of the string, which I did successfully. Conceptually, I wanted to know what is the difference between # and % and why do I need ## in the first example as opposed to just #. Why cannot I use # instead of %? Thanks.
# 2  
Old 09-05-2015
# means to mask the least possible from the beginning.
## means to mask as much as possible from the beginning.
*/ means any amount of chars or none, followed by a /
Thus, the result:
Code:
$ echo "${filename#*/}"
first/second/third/fourth

% means to mask the least possible from the end.
%% means to mask as much as possible from the end.
# 3  
Old 09-05-2015
Thank you! One more question, what is the concept name behind # and %? I want to search and learn more information about this, but not sure what to exactly look for. Are they string operators? Thanks again!
# 4  
Old 09-05-2015
Quote:
Originally Posted by shah9250
Thank you! One more question, what is the concept name behind # and %? I want to search and learn more information about this, but not sure what to exactly look for. Are they string operators? Thanks again!
Hello Shah9250,

This is called Parameter Expansion. You can check with man bash, it is very well defined there too. Following is the manual entry notes for same.
Code:
  Parameter Expansion
       The '$' character introduces parameter expansion, command substitution, or arithmetic expansion.  The parameter name or symbol  to  be  expanded
       may  be  enclosed  in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which
       could be interpreted as part of the name.
        When braces are used, the matching ending brace is the first '}' not escaped by a backslash or within a quoted string, and not within an  embed-
       ded arithmetic expansion, command substitution, or parameter expansion.
        ${parameter}
              The  value  of  parameter  is substituted.  The braces are required when parameter is a positional parameter with more than one digit, or
              when parameter is followed by a character which is not to be interpreted as part of its name.
        If the first character of parameter is an exclamation point, a level of variable indirection is introduced.  Bash uses the value of the variable
       formed  from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substi-
       tution, rather than the value of parameter itself.  This is known as indirect expansion.  The exceptions to this are the expansions  of  ${!pre-
       fix*} and ${!name[@]} described below.  The exclamation point must immediately follow the left brace in order to introduce indirection.
        In  each  of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.  When not
       performing substring expansion, bash tests for a parameter that is unset or null; omitting the colon results in a test only for a parameter that
       is unset.
        ${parameter:-word}
              Use  Default  Values.  If parameter is unset or null, the expansion of word is substituted.  Otherwise, the value of parameter is substi-
              tuted.
       ${parameter:=word}
              Assign Default Values.  If parameter is unset or null, the expansion of word is assigned to parameter.  The value of  parameter  is  then
              substituted.  Positional parameters and special parameters may not be assigned to in this way.
       ${parameter:?word}
              Display  Error  if  Null  or  Unset.   If  parameter  is null or unset, the expansion of word (or a message to that effect if word is not
              present) is written to the standard error and the shell, if it is not interactive, exits.  Otherwise, the value of parameter  is  substi-
              tuted.
       ${parameter:+word}
              Use Alternate Value.  If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
       ${parameter:offset}
       ${parameter:offset:length}
              Substring  Expansion.  Expands to up to length characters of parameter starting at the character specified by offset.  If length is omit-
              ted, expands to the substring of parameter starting at the character specified by offset.  length and offset are  arithmetic  expressions
              (see ARITHMETIC EVALUATION below).  length must evaluate to a number greater than or equal to zero.  If offset evaluates to a number less
              than zero, the value is used as an offset from the end of the value of parameter.  If parameter is @, the  result  is  length  positional
              parameters beginning at offset.  If parameter is an array name indexed by @ or *, the result is the length members of the array beginning
              with ${parameter[offset]}.  A negative offset is taken relative to one greater than the maximum index of the specified array.  Note  that
              a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion.  Substring index-
              ing is zero-based unless the positional parameters are used, in which case the indexing starts at 1.
        ${!prefix*}
       ${!prefix@}
              Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable.
        ${!name[@]}
       ${!name[*]}
              If name is an array variable, expands to the list of array indices (keys) assigned in name.  If name is not an array,  expands  to  0  if
              name is set and null otherwise.  When @ is used and the expansion appears within double quotes, each key expands to a separate word.
        ${#parameter}
              The  length in characters of the value of parameter is substituted.  If parameter is * or @, the value substituted is the number of posi-
              tional parameters.  If parameter is an array name subscripted by * or @, the value substituted is the number of elements in the array.
        ${parameter#word}
       ${parameter##word}
              The word is expanded to produce a pattern just as in pathname expansion.  If the pattern matches the beginning of the value of parameter,
              then  the  result  of the expansion is the expanded value of parameter with the shortest matching pattern (the ''#'' case) or the longest
              matching pattern (the ''##'' case) deleted.  If parameter is @ or *, the pattern removal operation is applied to each positional  parame-
              ter  in  turn,  and  the expansion is the resultant list.  If parameter is an array variable subscripted with @ or *, the pattern removal
              operation is applied to each member of the array in turn, and the expansion is the resultant list.
        ${parameter%word}
       ${parameter%%word}
              The word is expanded to produce a pattern just as in pathname expansion.  If the pattern matches a trailing portion of the expanded value
              of  parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ''%'' case) or
              the longest matching pattern (the ''%%'' case) deleted.  If parameter is @ or *, the pattern removal operation is applied to  each  posi-
              tional  parameter  in turn, and the expansion is the resultant list.  If parameter is an array variable subscripted with @ or *, the pat-
              tern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
        ${parameter/pattern/string}
              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 Ipattern 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.

You can try following links for same too, which may be helpful to you.
HowTo: Use Bash Parameter Substitution Like A Pro
Using Bash Shell Parameter Expansions

Enjoy learning Smilie


Thanks,
R. Singh

Last edited by Don Cragun; 09-05-2015 at 10:27 PM.. Reason: Change QUOTE tags to CODE tags to avoid smiley expansions.
 
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. AIX

Apache 2.4 directory cannot display "Last modified" "Size" "Description"

Hi 2 all, i have had AIX 7.2 :/# /usr/IBMAHS/bin/apachectl -v Server version: Apache/2.4.12 (Unix) Server built: May 25 2015 04:58:27 :/#:/# /usr/IBMAHS/bin/apachectl -M Loaded Modules: core_module (static) so_module (static) http_module (static) mpm_worker_module (static) ... (3 Replies)
Discussion started by: penchev
3 Replies

2. Shell Programming and Scripting

Bash script - Print an ascii file using specific font "Latin Modern Mono 12" "regular" "9"

Hello. System : opensuse leap 42.3 I have a bash script that build a text file. I would like the last command doing : print_cmd -o page-left=43 -o page-right=22 -o page-top=28 -o page-bottom=43 -o font=LatinModernMono12:regular:9 some_file.txt where : print_cmd ::= some printing... (1 Reply)
Discussion started by: jcdole
1 Replies

3. Shell Programming and Scripting

Delete all log files older than 10 day and whose first string of the first line is "MSH" or "<?xml"

Dear Ladies & Gents, I have a requirement to delete all the log files in /var/log/test directory that are older than 10 days and their first line begin with "MSH" or "<?xml" or "FHS". I've put together the following BASH script, but it's erroring out: for filename in $(find /var/log/test... (2 Replies)
Discussion started by: Hiroshi
2 Replies

4. UNIX for Dummies Questions & Answers

Using "mailx" command to read "to" and "cc" email addreses from input file

How to use "mailx" command to do e-mail reading the input file containing email address, where column 1 has name and column 2 containing “To” e-mail address and column 3 contains “cc” e-mail address to include with same email. Sample input file, email.txt Below is an sample code where... (2 Replies)
Discussion started by: asjaiswal
2 Replies

5. Shell Programming and Scripting

grep with "[" and "]" and "dot" within the search string

Hello. Following recommendations for one of my threads, this is working perfectly : #!/bin/bash CNT=$( grep -c -e "some text 1" -e "some text 2" -e "some text 3" "/tmp/log_file.txt" ) Now I need a grep success for some thing like : #!/bin/bash CNT=$( grep -c -e "some text_1... (4 Replies)
Discussion started by: jcdole
4 Replies

6. Shell Programming and Scripting

how to use "cut" or "awk" or "sed" to remove a string

logs: "/home/abc/public_html/index.php" "/home/abc/public_html/index.php" "/home/xyz/public_html/index.php" "/home/xyz/public_html/index.php" "/home/xyz/public_html/index.php" how to use "cut" or "awk" or "sed" to get the following result: abc abc xyz xyz xyz (8 Replies)
Discussion started by: timmywong
8 Replies

7. Shell Programming and Scripting

awk command to replace ";" with "|" and ""|" at diferent places in line of file

Hi, I have line in input file as below: 3G_CENTRAL;INDONESIA_(M)_TELKOMSEL;SPECIAL_WORLD_GRP_7_FA_2_TELKOMSEL My expected output for line in the file must be : "1-Radon1-cMOC_deg"|"LDIndex"|"3G_CENTRAL|INDONESIA_(M)_TELKOMSEL"|LAST|"SPECIAL_WORLD_GRP_7_FA_2_TELKOMSEL" Can someone... (7 Replies)
Discussion started by: shis100
7 Replies

8. Shell Programming and Scripting

cat $como_file | awk /^~/'{print $1","$2","$3","$4}' | sed -e 's/~//g'

hi All, cat file_name | awk /^~/'{print $1","$2","$3","$4}' | sed -e 's/~//g' Can this be done by using sed or awk alone (4 Replies)
Discussion started by: harshakusam
4 Replies

9. UNIX for Dummies Questions & Answers

Explain the line "mn_code=`env|grep "..mn"|awk -F"=" '{print $2}'`"

Hi Friends, Can any of you explain me about the below line of code? mn_code=`env|grep "..mn"|awk -F"=" '{print $2}'` Im not able to understand, what exactly it is doing :confused: Any help would be useful for me. Lokesha (4 Replies)
Discussion started by: Lokesha
4 Replies
Login or Register to Ask a Question