How to split long sed expression into multiple lines?

sed 's/[long1][long2]/[long3][long4]/' file.txt

I would like to split this command onto multiple lines – f.x. something like this:

sed 's/
    [long1]
    [long2]
  /
    [long3]
    [long4]
  /' file.txt

Using or separating strings didn’t work.

Asked By: Raffael

||

You can save long string to bash variables, then use in sed command:

string=[long1][long2]
replace=[long3][long4]
sed -e 's/'"$string"'/'"$replace"'/' file

If you can use perl, you can break long pattern with x modifier:

perl -e 's/
[long1]
[long2]
/[long3][long4]/x' file
Answered By: cuonglm
sed 's'/
'[long1]'
'[long2]'
'/'
'[long3]'
'[long4]'
'/' file.txt

Splitting on several lines with backslash does work if new lines are not indented.

$ echo "a,b" | sed 's/(.'
> '),(.)/2-1/'
b-a

Tested on Cygwin with GNU sed 4.2.2

Answered By: Raffael

You can also break that up this way:

sed '/[long1][long2]/
    s//[long3][long4]/'

Or maybe like:

sed "$(
    printf 's/[%s][%s]/[%s][%s]/' 
        long1 
        long2 
        long3 
        long4
)"

Or with a heredoc:

sed -f - <<SED file.txt
s/
[long1]
[long2]
/
[long3]
[long4]
/
SED
Answered By: mikeserv

Another aspect:

How maintainable are the [long] items above?

The shorter and more distinct you can keep the clauses, the easier they will be to change and enhance as time passes and (sed-external) facts change around the the function they provide.

e.g.

sed 
-e 's/[minimal-s1]/[minimal-r1]/' 
-e 's/[minimal-s2]/[minimal-r2]/' 
-e 's/[minimal-s3]/[minimal-r3]/' 
-e 's/[minimal-s4]/[minimal-r4]/' 

… might be something to strive for and prefer.

Answered By: Hannu
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.