I have a text file with the following format. The first line is the \"KEY\" and the second line is the \"VALUE\".
KEY 4048:1736 string
3
KEY 0:1772 string
1
If Perl is an option, you can try:
perl -0pe 's/(.*)\n(.*)\n/$1 $2\n/g' file.txt
Another solutions using vim (just for reference).
Solution 1:
Open file in vim vim filename
, then execute command :% normal Jj
This command is very easy to understand:
After that, save the file and exit with :wq
Solution 2:
Execute the command in shell, vim -c ":% normal Jj" filename
, then save the file and exit with :wq
.
You can also use the following vi command:
:%g/.*/j
"ex" is a scriptable line editor that is in the same family as sed, awk, grep, etc. I think it might be what you are looking for. Many modern vi clone/successors also have a vi mode.
ex -c "%g/KEY/j" -c "wq" data.txt
This says for each line, if it matches "KEY" perform a j oin of the following line. After that command completes (against all lines), issue a w rite and q uit.
awk:
awk 'NR%2{printf "%s ",$0;next;}1' yourFile
note, there is an empty line at the end of output.
sed:
sed 'N;s/\n/ /' yourFile
Here is another way with awk
:
awk 'ORS=NR%2?FS:RS' file
$ cat file
KEY 4048:1736 string
3
KEY 0:1772 string
1
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1
$ awk 'ORS=NR%2?FS:RS' file
KEY 4048:1736 string 3
KEY 0:1772 string 1
KEY 4192:1349 string 1
KEY 7329:2407 string 2
KEY 0:1774 string 1
As indicated by Ed Morton in the comments, it is better to add braces for safety and parens for portability.
awk '{ ORS = (NR%2 ? FS : RS) } 1' file
ORS
stands for Output Record Separator. What we are doing here is testing a condition using the NR
which stores the line number. If the modulo of NR
is a true value (>0) then we set the Output Field Separator to the value of FS
(Field Separator) which by default is space, else we assign the value of RS
(Record Separator) which is newline.
If you wish to add ,
as the separator then use the following:
awk '{ ORS = (NR%2 ? "," : RS) } 1' file