Thread: Bash: Assigning a substring to a variable

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912

    Bash: Assigning a substring to a variable

    I've been learning bash scripting, but unfortunately it's more out of necessity than taking my time and learning the meaning of all the syntax really well. I've run into a problem that I can't seem to figure out from any documentation - so if anyone can shed some light on this I'd be appreciative.

    I have a loop where I need to loop through all the files, and do several different things with the part of the filename before the extension. The first 'echo' statement below outputs exactly what I need, however since I do several different actions with that output, I really need it to be stored in it's own variable.

    Code:
    for file in `ls *.txt `
    do
    	# outputs the desired result, but I need it in a variable
    	echo `expr "$file" : '\([^.]\+\)'`
    
    	# this either tries to execute the result or yields a '0'
    	let s=`expr "$file" : '\([^.]\+\)'`
    	echo $s
    done

    My first thought was the 'let' and the second echo, but that results in a '0'. I've also tried wrapping the expression in a $( ... ) but that yields '0' if I remove the back ticks, and tries to execute the result as a command if I leave the backticks. I also initially thought that having slashes in the file path was causing it to be evaluated differently, but I modified the program so there are no longer any slashes in the path - just the filename.

    Any thoughts?

  2. #2
    Registered User
    Join Date
    Dec 2008
    Location
    Black River
    Posts
    128
    You should be able to assign the first expression you're echoing to a variable:

    Code:
    for file in `ls *.txt `; do
        x=`expr "$file" : '\([^.]\+\)'`
        echo $x
    done
    Stick close to your desks and never program a thing,
    And you all may sit in the standards commitee!

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Well what'd'ya know, that worked! I knew I was missing the point of something, but I wouldn't have thought it would be something as simple as the real meaning of 'let'. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C variable
    By webstarsandeep in forum C Programming
    Replies: 1
    Last Post: 10-23-2008, 01:26 AM
  2. Assigning Binary Value to a Variable
    By JAYMAN in forum C Programming
    Replies: 2
    Last Post: 11-06-2005, 01:24 PM
  3. static class variable vs. global variable
    By nadamson6 in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2005, 03:31 PM
  4. Variable assigning Functions
    By emus21 in forum C Programming
    Replies: 4
    Last Post: 11-09-2003, 01:13 AM
  5. Variable Allocation in a simple operating system
    By awkeller in forum C Programming
    Replies: 1
    Last Post: 12-08-2001, 02:26 PM