How to read output of sed into a variable

前端 未结 4 1766
野性不改
野性不改 2020-12-13 23:28

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

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

相关标签:
4条回答
  • 2020-12-13 23:48

    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.

    0 讨论(0)
  • 2020-12-13 23:56

    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/'`
    
    0 讨论(0)
  • 2020-12-14 00:06

    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"
    
    0 讨论(0)
  • 2020-12-14 00:07

    if you have Bash/ksh

    $ var="abcd.txt"
    $ echo ${var%.txt}.log
    abcd.log
    $ variable=${var%.txt}.log
    
    0 讨论(0)
提交回复
热议问题