Reputation: 1280
I have a file that holds output from a test.
test 1
42
test 2
69
test 3
420
test 4
55378008
I would like to make the test output appear on the same line as the test name. like so:
test 1: 42
test 2: 69
test 3: 420
test 4: 55378008
I am sure there is some fancy sed
, awk
or perl
way to do this but I am stuck.
Upvotes: 3
Views: 261
Reputation: 6798
Bash solution
skips empty lines
process both UNIX/DOS format 'end of line'
accepts filename as argument or otherwise reads data from STDIN
#!/bin/bash
while read p1
do
[[ -z $p1 ]] && continue
# p1=`echo -n $p1 | tr -d "\r"` # replaced with following line
p1=${p1//$'\r'/}
read p2
echo -n "$p1: $p2"
done < ${1:-/dev/stdin}
Output
test 1: 42
test 2: 69
test 3: 420
test 4: 55378008
NOTE: no empty lines allowed between lines for join
Upvotes: 0
Reputation: 385590
Just replace the line feed of odd lines with :␠
.
perl -pe's/\n/: / if $. % 2'
You have mentioned that you want to removing leading and trailing whitespace as well. For that, you can use the following:
perl -pe's/^\h+|\h+$/g; s/\n/: / if $. % 2'
Specifying file to process to Perl one-liner
Upvotes: 2
Reputation: 7781
A shell solution, which is very slow
on large set of data/files.
while IFS= read -r odd_line; do
IFS= read -r even_line
printf '%s: %s\n' "$odd_line" "$even_line"
done < file.txt
On the other hand if the colon is not a requirement paste
can do the job.
paste - - < file.txt
Upvotes: 1
Reputation: 23667
pr
has this built-in, but if you need whitespace adjustment as well, then sed/awk/perl
solutions suggested in other answers will suit you better
$ pr -2ats': ' ip.txt
test 1: 42
test 2: 69
test 3: 420
test 4: 55378008
This combines 2 lines at a time with :
as the separator.
Upvotes: 3
Reputation: 1117
And here is another one in sed flavor to complete the offer :
sed 'N ; s/\n/: /' input_file
For each (odd) line starting from the first, append the next (even) one in pattern space separated by a LF, then just replace this LF by :
.
Upvotes: 5
Reputation: 4688
awk 'FNR%2{printf "%s: ", $0; next}1' file
This prints odd lines with suffix :
and without newline and even lines with a newline.
Upvotes: 3