63

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Roger Moore
  • 1,071
  • 3
  • 11
  • 8

4 Answers4

101

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
  • 445,704
  • 82
  • 492
  • 529
  • 2
    even better: `new_filename="$(echo "$a" | sed 's/.txt/.log/')"` (in Bash pairs of `" "` inside command substitution still match). – Benoit Oct 25 '10 at 11:29
  • 1
    "Less recommended"? Maybe for bash, but the shell hasn't been specified, so it may be the only option :-) – Chris J Oct 25 '10 at 12:17
21

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
  • 51,692
  • 2
  • 65
  • 86
  • As I understand it, you are supposed to use *Bash Command Substitution*, not back ticks. Also see [Quoting within $(command substitution) in Bash](https://unix.stackexchange.com/q/118433/56041), [Command substitution with string substitution](https://stackoverflow.com/q/30146466/608639) and friends. – jww Mar 12 '18 at 21:38
5

The simplest way is

logfile="${a/\.txt/\.log}"

If it should be allowed that the filename in $a has more than one occurrence of .txt in it, use the following solution. Its more safe. It only changes the last occurrence of .txt

logfile="${a%%\.txt}.log"
Adrian W
  • 4,563
  • 11
  • 38
  • 52
ikke dus
  • 76
  • 1
  • 2
3

if you have Bash/ksh

$ var="abcd.txt"
$ echo ${var%.txt}.log
abcd.log
$ variable=${var%.txt}.log
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 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 Oct 25 '10 at 12:14