How to read output of sed into a variable

ShellVariablesSed

Shell Problem Overview


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?

Shell Solutions


Solution 1 - Shell

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/'`

Solution 2 - Shell

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.

Solution 3 - Shell

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"

Solution 4 - Shell

if you have Bash/ksh

$ var="abcd.txt"
$ echo ${var%.txt}.log
abcd.log
$ variable=${var%.txt}.log

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoger MooreView Question on Stackoverflow
Solution 1 - ShellcodaddictView Answer on Stackoverflow
Solution 2 - ShellCameron SkinnerView Answer on Stackoverflow
Solution 3 - Shellikke dusView Answer on Stackoverflow
Solution 4 - Shellghostdog74View Answer on Stackoverflow