siemanko
siemanko

Reputation: 1409

Line breaking in bash script

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.

Upvotes: 7

Views: 18526

Answers (3)

Swiss
Swiss

Reputation: 5829

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'

Upvotes: 8

Alexander Putilin
Alexander Putilin

Reputation: 2342

Just insert backslash character before a newline:

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

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

Use the shell continuation character, which is normally \.

[~]$ foo \
> and \
> bar

Space is not required:

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

Upvotes: 1

Related Questions