tags:

views:

46

answers:

3

I have variable which has value "abcd.txt".

I want to store everything before the ".txt" in a second variable, replacing the ".txt" with ".log"

I have no problem echoing the desired value:

a="abcd.txt"

echo $a | sed 's/.txt/.log/'

But how do I get the value "abcd.log" into the second variable?

Thanks,

Roger

+4  A: 

You can use command substitution as:

new_filename=$(echo "$a" | sed 's/.txt/.log/')

or the less recommended backtick way:

new_filename=`echo "$a" | sed 's/.txt/.log/'`
codaddict
even better: `new_filename="$(echo "$a" | sed 's/.txt/.log/')"` (in Bash pairs of `" "` inside command substitution still match).
Benoit
"Less recommended"? Maybe for bash, but the shell hasn't been specified, so it may be the only option :-)
Chris J
@Chris: You are right..
codaddict
Thanks very much!
Roger Moore
A: 

You can use backticks to assign the output of a command to a variable:

logfile=`echo $a | sed 's/.txt/.log/'`

That's assuming you're using Bash.

Alternatively, for this particular problem Bash has pattern matching constructs itself:

stem=$(textfile%%.txt)
logfile=$(stem).log

or

logfile=$(textfile/%.txt/.log)

The % in the last example will ensure only the last .txt is replaced.

Cameron Skinner
Thank you for the tips.
Roger Moore
+1  A: 

if you have Bash/ksh

$ var="abcd.txt"
$ echo ${var%.txt}.log
abcd.log
$ variable=${var%.txt}.log
ghostdog74
Thanks, but this does not get me anywhere...I was already able to echo...the problem is I want to get it into a variable.
Roger Moore
if you want to get it into variable, just assign it? declaring and assigning variables are VERY basic stuff in shell scripting, i doubt you don't know how to do it.
ghostdog74