Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
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/
  /' file.txt

Using \ or separating strings didn't work.

share|improve this question
That's why Perl has the /x modifier to substitution. – choroba Jul 28 '14 at 10:38
@Networker: yes, thanks, I added my answer there, too – Raffael Jul 28 '14 at 20:57

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

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/
/[long3][long4]/x' file
share|improve this answer
Why do you use so many quotes? sed "s/$string/$replace/" file.txt is fine. – Scott Jul 28 '14 at 20:50
Also, of course, you need to delete the space after replace=. – Scott Jul 28 '14 at 20:51
up vote 5 down vote accepted
sed 's'/\
'/' file.txt

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

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

Tested on Cygwin with GNU sed 4.2.2

share|improve this answer
What is your sed version? I test with GNU sed version 4.2.1 and it does not work. – cuonglm Jul 28 '14 at 11:09
Looks like there is a backslash missing at the end of first line, fter the slash? – Volker Siegel Jul 28 '14 at 19:54

You can also break that up this way:

sed '/[long1][long2]/

Or maybe like:

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

Or with a heredoc:

sed -f - <<SED file.txt
share|improve this answer

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.


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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.