Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find line starts with and replace in linux using sed [duplicate]

How do I find line starts with and replace complete line?

File output:

 xyz
 abc
 /dev/linux-test1/

Code:

output=/dev/sda/windows
sed 's/^/dev/linux*/$output/g' file.txt

I am getting below Error:

 sed: -e expression #1, char 9: unknown option to `s'

File Output expected after replacement:

 xyz
 abc
 /dev/sda/windows
like image 893
asteroid4u Avatar asked Nov 21 '25 07:11

asteroid4u


1 Answers

Let's take this in small steps.

First we try changing "dev" to "other":

sed 's/dev/other/' file.txt
/other/linux-test1/

(Omitting the other lines.) So far, so good. Now "/dev/" => "/other/":

sed 's//dev///other//' file.txt
sed: 1: "s//dev///other//": bad flag in substitute command: '/'

Ah, it's confused, we're using '/' as both a command delimiter and literal text. So we use a different delimiter, like '|':

sed 's|/dev/|/other/|' file.txt
/other/linux-test1/

Good. Now we try to replace the whole line:

sed 's|^/dev/linux*|/other/|' file.txt
/other/-test1/

It didn't replace the whole line... Ah, in sed, '*' means the previous character repeated any number of times. So we precede it with '.', which means any character:

sed 's|^/dev/linux.*|/other/|' file.txt
/other/

Now to introduce the variable:

sed 's|^/dev/linux.*|$output|' file.txt
$output

The shell didn't expand the variable, because of the single quotes. We change to double quotes:

sed "s|^/dev/linux.*|$output|" file.txt
/dev/sda/windows
like image 108
Beta Avatar answered Nov 23 '25 19:11

Beta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!