user3397008
user3397008

Reputation: 100

Append to same line using grep

I have a file with multiple lines. I'm trying to find lines that match a certain pattern and then get them appended to an output file, all on the same.

Ex: Input file:

ABCD 
other text
EFGH
other text
IJKLM

I'm trying to get the output to be :

ABCD EFGH IJKLM

Upvotes: 0

Views: 3759

Answers (4)

Jotne
Jotne

Reputation: 41456

Here is an short awk

awk 'NR%2==1' ORS=" " file
ABCD EFGH IJKLM

It will print every second line into one line.

Upvotes: 0

janos
janos

Reputation: 124646

An easy way to make grep output matches separated by spaces instead of newlines is to wrap it in a sub-shell with $(...) like this:

echo $(grep -o '^[A-Z]*$' input.txt) >> output.txt

Or you could use tr:

grep -o '^[A-Z]*$' input.txt | tr '\n' ' ' >> output.txt

Or perl:

grep -o '^[A-Z]*$' input.txt | perl -pe 'chomp; s/$/ /'

Upvotes: 1

clt60
clt60

Reputation: 63902

If you like perl, you can also

perl -nl40e 'print if /PATTERN/' files....

like

perl -nl40e 'print if /[A-Z]/' file

for your input produces

ABCD EFGH IJKLM

Upvotes: 0

Adam Liss
Adam Liss

Reputation: 48290

You can use tr to translate the newlines to spaces:

grep $EXPRESSION $INPUT_FILE | tr '\n' ' ' >> $OUTPUT_FILE

Upvotes: 1

Related Questions