首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在变量- Bash/Shell脚本中插入换行符

在变量- Bash/Shell脚本中插入换行符
EN

Stack Overflow用户
提问于 2019-11-22 23:18:56
回答 2查看 60关注 0票数 0

我有一个包含shell命令输出的变量,我试图'grep‘这个变量,但似乎所有的输出都在一行中,没有换行。所以当我'grep‘这个变量时,所有的东西都会被返回。

例如,我的变量包含以下内容:

代码语言:javascript
复制
 standalone 123 abc greefree ten1 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 

我想在有ten1或ten2的地方插入换行符。因此,当我'grep‘变量时,我只返回一个特定的行。

如下所示的输出

代码语言:javascript
复制
standalone 123 abc greefree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2

有没有可以使用的bash命令或某种类型的regex表达式?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-22 23:35:29

你能不能试着跟着我走一遍。

代码语言:javascript
复制
sed 's/\r//g;s/ten[12]/&\n/g' Input_file

要在最后一次尝试删除空格(将保留在上面的代码中):

代码语言:javascript
复制
sed -E 's/\r//g;s/ten[12]/&\n/g'  Input_file | sed -E 's/^ +//'

基于多个图案进行编辑

代码语言:javascript
复制
sed -e 's/\r//g;s/ten[12]/&\n/g' -e 's/\r//g;s/abc[12]/&\n/g' Input_file
票数 1
EN

Stack Overflow用户

发布于 2019-11-22 23:36:32

下面是sed和tr的组合,它可能会让你更接近你想要的:

代码语言:javascript
复制
sed -e 's/ten1/^M/g' -e 's/ten2/^M/g' | tr \\r \\n

假设你有一个名为LONG的变量,你可以使用上面的代码,如下所示:

代码语言:javascript
复制
echo "$LONG" | sed -e 's/ten1/^M/g' -e 's/ten2/^M/g' | tr \\r \\n

上面,我们将所有的ten1和ten2字符串转换为CR (回车),然后使用tr将这些CR转换为换行符。将grep放在after语句中:

代码语言:javascript
复制
echo "$LONG" | sed -e 's/ten1/^M/g' -e 's/ten2/^M/g' | tr \\r \\n | grep whatever

在重新阅读了您的问题和其他答案之后,我提供了这段代码,以包括原始的ten1或ten2:

代码语言:javascript
复制
 echo "$LONG" | sed 's/ten[12] /&^M/g'  | tr \\r \\n

这是输出:

代码语言:javascript
复制
standalone 123 abc greefree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58997142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档