Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read output of sed into a variable

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?

like image 668
Roger Moore Avatar asked Oct 25 '10 11:10

Roger Moore


People also ask

Can you use sed on a 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.

How do you use sed on a specific line?

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.

What is I flag in sed?

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.


1 Answers

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/'` 
like image 95
codaddict Avatar answered Sep 21 '22 18:09

codaddict