如何将sed的输出读入变量

时间:2022-12-27 15:46:19

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

我有变量值“abcd.txt”。

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

我想将“.txt”之前的所有内容存储在第二个变量中,将“.txt”替换为“.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?

但是如何将值“abcd.log”输入第二个变量?

4 个解决方案

#1


52  

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

#2


11  

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.

假设你正在使用Bash。

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

或者,对于这个特殊问题,Bash本身就有模式匹配结构:

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

or

要么

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

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

最后一个示例中的%将确保仅替换最后一个.txt。

#3


3  

if you have Bash/ksh

如果你有Bash / ksh

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

#4


1  

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

如果应该允许$ a中的文件名中出现多个.txt,请使用以下解决方案。它更安全。它只会更改最后一次出现的.txt

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

#1


52  

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

#2


11  

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.

假设你正在使用Bash。

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

或者,对于这个特殊问题,Bash本身就有模式匹配结构:

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

or

要么

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

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

最后一个示例中的%将确保仅替换最后一个.txt。

#3


3  

if you have Bash/ksh

如果你有Bash / ksh

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

#4


1  

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

如果应该允许$ a中的文件名中出现多个.txt,请使用以下解决方案。它更安全。它只会更改最后一次出现的.txt

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