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?
The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.
Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.
The I flag allows to match a pattern case insensitively. Usually i is used for such purposes, grep -i for example. But i is a command (discussed in append, change, insert chapter) in sed , so /REGEXP/i cannot be used.
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/'`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With