bash 脚本中的换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11838179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:56:53  来源:igfitidea点击:

Line breaking in bash script

bashnewline

提问by siemanko

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

在我的公司风格指南中,它说 bash 脚本不能超过 80 行。所以我有两倍长的这个巨大的 sed 替代。我怎样才能将它分成更多行以使其仍然有效?我有

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.

仍然具有相同的效果。

回答by Swiss

Possible ways to clean up

可能的清理方法

1) Put your sed script into a file

1) 将你的 sed 脚本放入一个文件中

sed -f script [file ...]

2) Use Regex shorthand

2) 使用 Regex 简写

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

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

3) 使用 Bash 变量来帮助分解一下

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.

1)转义换行符以将其分解为多行。

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

您最终会在 sed 脚本中出现一个您不想要的换行符。

sed 's/THIS IS WRONG /\
AND WILL BREAK YOUR SCRIPT/g'

回答by Burhan Khalid

Use the shell continuation character, which is normally \.

使用 shell 继续符,通常是\.

[~]$ foo \
> and \
> bar

Space is not required:

不需要空格:

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

回答by Alexander Putilin

Just insert backslash character before a newline:

只需在换行符之前插入反斜杠字符:

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