Hi,

I am trying to replace the old_string with the new_string using sed.
But i am unable to do it using the following script.

#!/bin/sh

old_string="p cnf 10 20"
new_string="p cnf 98 99"

sed -e 's/old_string/new_string/' file1.txt > file2.txt

Contents of file1.txt

p cnf 10 20
1 2 3
4 5 6
8 9 10
11 12 30

Any help is appreciated.

Dani AI

Generated

The immediate problem in the first post is quoting: the shell does not expand variables inside single quotes, so sed saw a literal script instead of the contents of your variables. pointed toward double quotes, which is the right idea; expand on that and watch for characters that are special to the sed script (slashes, ampersands, backslashes, etc.). A robust, simple approach is to use an alternate delimiter so you do not have to backslash slashes in the data:

sed "s|$old_string|$new_string|g" file1.txt > file2.txt

If the variables can contain regex metacharacters or &, escape them first or use a tool that treats the match as literal. One practical approach is Perl with quotemeta so you do not have to write an escape routine yourself:

export OLD="$old_string"
export NEW="$new_string"
perl -pe 'BEGIN { $o = quotemeta($ENV{"OLD"}); $n = $ENV{"NEW"} } s/$o/$n/g' file1.txt > file2.txt

For : the N-then-substitute pattern is the correct idea—N appends the next line into the pattern space and you remove the embedded newline. If your command seemed to fail, check for CRLFs (Windows line endings) or for wanting repeated joins when there are multiple non-; lines in a row. Convert CRLFs first or strip \r, and use a one-liner such as:

sed 's/\r$//' inputfile | sed '/;$/!{N;s/\n//;}' > outputfile

Read about the N command and its behavior in the GNU sed manual for details and edge cases: GNU sed manual.

Recommended Answers

All 2 Replies

sed -e "s/$old_string/$new_string/" file1.txt > file2.txt

I have a little sed problem which I can't seem to figure out:
I would like to concatenate the next line of a file to the current line if the current line doesn't end in ;
I tried the next command but it doesn't seem to work:

sed '/[^;]$/{N;s/\n//;}'

Any ideas?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.