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
paste
is good for this job:
paste -d " " - - < filename
You can use awk like this to combine ever 2 pair of lines:
awk '{ if (NR%2 != 0) line=$0; else {printf("%s %s\n", line, $0); line="";} } \
END {if (length(line)) print line;}' flle
Alternative to sed, awk, grep:
xargs -n2 -d'\n'
This is best when you want to join N lines and you only need space delimited output.
My original answer was xargs -n2
which separates on words rather than lines. -d
can be used to split the input by any single character.
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
string1=x
string2=y
string3
string4
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
string1=x string2=y
string3
string4
A more-general solution (allows for more than one follow-up line to be joined) as a shell script. This adds a line between each, because I needed visibility, but that is easily remedied. This example is where the "key" line ended in : and no other lines did.
#!/bin/bash
#
# join "The rest of the story" when the first line of each story
# matches $PATTERN
# Nice for looking for specific changes in bart output
#
PATTERN='*:';
LINEOUT=""
while read line; do
case $line in
$PATTERN)
echo ""
echo $LINEOUT
LINEOUT="$line"
;;
"")
LINEOUT=""
echo ""
;;
*) LINEOUT="$LINEOUT $line"
;;
esac
done
Try the following line:
while read line1; do read line2; echo "$line1 $line2"; done <old.txt>new_file
Put delimiter in-between
"$line1 $line2";
e.g. if the delimiter is |
, then:
"$line1|$line2";