0

I have a file containing:

L1
L2
L3
.
.
.
L512

I want to change its content to :

L1 | L2 | L3 | ... | L512

It seems so easy , but its now 1 hour Im sitting and trying to make it, I tried to do it by sed, but didn't get what I want. It seems that sed just inserts empty lines between the content, any suggestion please?

KianStar
  • 177
  • 1
  • 9

5 Answers5

1

Here is one sed

sed ':a;N;s/\n/ | /g;ta' file
L1 | L2 | L3 | ... | L512

And one awk

awk '{printf("%s%s",sep,$0);sep=" | "} END {print ""}' file
L1 | L2 | L3 | ... | L512
Jotne
  • 40,548
  • 12
  • 51
  • 55
1

With sed this requires to read the whole input into a buffer and afterwards replace all newlines by |, like this:

sed ':a;N;$!ba;s/\n/ | /g' input.txt

Part 1 - buffering input

:a defines a label called 'a' N gets the next line from input and appends it to the pattern buffer $!ba jumps to a unless the end of input is reached

Part 2 - replacing newlines by |

s/\n/|/ execute the substitute command on the pattern buffern


As you can see, this is very inefficient since it requires to:

  • read the complete input into memory
  • operate three times on the input: 1. reading, 2. substituting, 3. printing

Therefore I would suggest to use awk which can do it in one loop:

awk 'NR==1{printf $0;next}{printf " | "$0}END{print ""}' input.txt
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0
perl -pe 's/\n/ |/g unless(eof)' file
Vijay
  • 65,327
  • 90
  • 227
  • 319
0

if space between | is not mandatory

tr "\n" '|' YourFile
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
  • 1
    This is just the same as Wintermute posted and gives an extra `|` at end of line, and does not give space around `|` – Jotne Jan 22 '15 at 12:58
  • 1
    sorry didn't see Wintermute answer (and still not). Good point for the last `|` so it need at least a pipe sequence wioth a sed or similar. – NeronLeVelu Jan 22 '15 at 13:42
  • Wintermute did delete his anwer since it did not give correct output. If you have more than 10000 points you can see the deleted answer. – Jotne Jan 22 '15 at 15:56
-1

Several options, including those mentioned here:

paste -sd'|' file
sed ':a;N;s/\n/ | /g;ta' file
sed ':a;N;$!ba;s/\n/ | /g' file
perl -0pe 's/\n/ | /g;s/ \| $/\n/' file
perl -0nE 'say join " | ", split /\n/' file
perl -E 'chomp(@x=<>); say join " | ", @x' file
mapfile -t ary < file; (IFS="|"; echo "${ary[*]}")
awk '{printf("%s%s",sep,$0);sep=" | "} END {print ""}' file
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • `past` does not work with `|`. This is just a collection of others post here :( (except perl and map) – Jotne Jan 22 '15 at 11:50