Join lines based on pattern

2019-02-24 21:05发布

I have the following file:

test
1
My
2
Hi
3

i need a way to use cat ,grep or awk to give the following output:

test1
My2
Hi3

How can i achieve this in a single command? something like

cat file.txt | grep ... | awk ...

Note that its always a string followed by a number in the original text file.

5条回答
小情绪 Triste *
2楼-- · 2019-02-24 21:38

Here is the answer: cat file.txt | awk 'BEGIN { lno = 0 } { val=$0; if (lno % 2 == 1) {printf "%s\n", $0} else {printf "%s", $0}; ++lno}'

查看更多
Anthone
3楼-- · 2019-02-24 21:41
paste -d "" - - < filename

This takes consecutive lines and pastes them together delimited by the empty string.

查看更多
太酷不给撩
4楼-- · 2019-02-24 21:48

sed 'N;s/\n//' file.txt

This should give the desired output when the content is in file.txt

查看更多
Viruses.
5楼-- · 2019-02-24 21:50
awk '{printf("%s", $0);} !(NR%2){printf("\n");}' file.txt


EDIT: I just noticed that your question requires the use of cat and grep. Both of those programs are unnecessary to achieve your stated aims. If you have some reason for including them that you haven't mentioned, try this (uselessly inefficient) version of the line I wrote immediately above:

cat file.txt | grep '^' | awk '{printf("%s", $0);} !(NR%2){printf("\n");}'

It is possible that this command uses features not present in the original awk program. You may need to invoke the new awk program, nawk instead.

查看更多
狗以群分
6楼-- · 2019-02-24 22:00

If your input file is always 1 number then 1 string, and you only want the strings, all you have to do is take every other line.

If you only want the odd lines, you can do awk 'NR % 2' file.txt

If you want the evens, this becomes awk 'NR % 2==0' data

查看更多
登录 后发表回答