[英]Find a line with certain string then remove it's newline character at the end in bash
I'm trying to prepare a file for a report.我正在尝试为报告准备文件。 What I have is like this:
我所拥有的是这样的:
foo
bar bar oof
bar oof
foo
bar bar
I'm trying to get an output like this:我试图得到这样的输出:
foo bar bar oof
bar off
foo bar bar
I wanted to search for a string, in this case 'foo', and within the line where the string is found I have to remove the newline.我想搜索一个字符串,在这种情况下是 'foo',并且在找到该字符串的行内,我必须删除换行符。
I did search but I can only find solutions where 'foo' is also removed.我做了搜索,但我只能找到“foo”也被删除的解决方案。 How can I do this?
我怎样才能做到这一点?
Using awk
:使用
awk
:
awk -v search='foo' '$0 ~ search{printf $0; next}1' infile
You may use printf $0 OFS
like below, if your field doesn't have leading space before newline char如果您的字段在换行符之前没有前导空格,您可以使用
printf $0 OFS
如下所示
awk -v search='foo' '$0 ~ search{printf $0 OFS; next}1' infile
Test Results:检测结果:
$ cat infile
foo
bar bar oof
bar oof
foo
bar bar
$ awk -v search='foo' '$0 ~ search{printf $0; next}1' infile
foo bar bar oof
bar oof
foo bar bar
Explanation:解释:
-v search='foo'
- set variable search
-v search='foo'
- 设置变量search
$0 ~ search
- if lines/record/row contains regexp/pattern/string mentioned in variable $0 ~ search
- 如果行/记录/行包含变量中提到的正则表达式/模式/字符串{printf $0; next}
{printf $0; next}
- print current record without record separator and go to next line {printf $0; next}
- 不带记录分隔符打印当前记录并转到下一行}1
1 at the end does default operation that is print current record/row. }1
1 最后执行默认操作,即打印当前记录/行。You can do this quite easily with sed
, for example:您可以使用
sed
轻松完成此操作,例如:
$ sed '/^foo$/N;s/\n/ /' file
foo bar bar oof
bar oof
foo bar bar
Explanation解释
/^foo$/
find lines containing only foo
/^foo$/
查找仅包含foo
N
read/append next line of input into pattern space. N
读取/追加下一行输入到模式空间。
s/\\n/ /
substitute the '\\n'
with a space
. s/\\n/ /
将'\\n'
替换为space
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.