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.
I did search but I can only find solutions where 'foo' is also removed. How can I do this?
Using 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
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
$0 ~ search
- if lines/record/row contains regexp/pattern/string mentioned in variable {printf $0; next}
{printf $0; next}
- print current record without record separator and go to next line }1
1 at the end does default operation that is print current record/row. You can do this quite easily with sed
, for example:
$ sed '/^foo$/N;s/\n/ /' file
foo bar bar oof
bar oof
foo bar bar
Explanation
/^foo$/
find lines containing only foo
N
read/append next line of input into pattern space.
s/\\n/ /
substitute the '\\n'
with a space
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.