7

In my company style guide it says that bash scripts cannot be longer than 80 lines. So I have this gigantic sed substitution over twice as long. How can I break it into more lines so that it still works? I have

sed -i s/AAAAA...AAA/BBBBB...BBB/g

And I want something like

sed -i s/AAAAA...AAA/
BBBBB...BBB/g

still having the same effect.

4
  • 80 columns, that's an old legacy requirement... Commented Aug 7, 2012 at 1:44
  • @jordanm If you're over 80 columns long in a bash script, 99% of the time you're doing something wrong. Commented Aug 7, 2012 at 1:47
  • 2
    @Swiss - it's very easy to do with pipes to awk Commented Aug 7, 2012 at 2:01
  • @jordanm You description sounds like it could possibly be cleaned up. Awk is a scripting language, so complicated Awk scripts are better put in their own file as is done with Perl scripts. More importantly, you can break a command with pipes up into multiple lines without even needing to escape the newline. Commented Aug 7, 2012 at 3:59

3 Answers 3

8

Possible ways to clean up

1) Put your sed script into a file

sed -f script [file ...]

2) Use Regex shorthand

sed 's!A\{30,\}!BBBBB...BBBB!g'

3) Use Bash variables to help break it up a bit

regex="AAAA.AAAAAA"
replace="BBBB...BBBBBBB"
sed "s/${regex}/${replace}/g"

What not to do

1) Escape the newline to break it up into multiple lines.

You will end up with a newline in your sed script that you don't want.

sed 's/THIS IS WRONG /\
AND WILL BREAK YOUR SCRIPT/g'
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Yeap, this is the right way; especially with sed in the context of scripts.
1

Use the shell continuation character, which is normally \.

[~]$ foo \
> and \
> bar

Space is not required:

[~]$ foo\
> and\
> bar\
> zoo\
> no space\
> whee!\

1 Comment

yes but that requires space to be inserted before it is used. I do not have this luxury with sed substitution :(
1

Just insert backslash character before a newline:

sed -i s/AAAAA...AAA/\
BBBBB...BBB/g

2 Comments

yes but that requires space to be inserted before it is used. I do not have this luxury with sed substitution :(
Works for me without any spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.