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
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1
I need the value in the same line as of the key. So the output should look like this...
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
It will be better if I could use some delimiter like $
or ,
:
KEY 4048:1736 string , 3
How do I merge two lines into one?
paste
is good for this job:You can use awk like this to combine ever 2 pair of lines:
awk:
note, there is an empty line at the end of output.
sed:
Try the following line:
Put delimiter in-between
e.g. if the delimiter is
|
, then:-0
gobbles the whole file instead of reading it line-by-line;pE
wraps code with loop and prints the output, see details in http://perldoc.perl.org/perlrun.html;^KEY
match "KEY" in the beginning of line, followed by non-greedy match of anything (.*?
) before sequence of\s+
of any kind including line breaks;(\d+)
which we capture and later re-insert as$1
;followed by the end of line
$
.\K
conveniently excludes everything on its left hand side from substitution so{ $1}
replaces only 1-2 sequence, see http://perldoc.perl.org/perlre.html.In the case where I needed to combine two lines (for easier processing), but allow the data past the specific, I found this to be useful
data.txt
cat data.txt | nawk '$0 ~ /string1=/ { printf "%s ", $0; getline; printf "%s\n", $0; getline } { print }' > converted_data.txt
output then looks like:
converted_data.txt