Replacing new line character with a pipe and a new line character
9,162
Solution 1
Unless you have joined lines, the \n
doesn't appear in sed
's pattern space: the end-of-line anchor is $
.
So with GNU sed:
sed -i 's/$/|/' temp.txt
Solution 2
You can use paste
:
$ :|paste -d'|' file - > new_file
one|two|three|four|five|
abc|def|pqr|lmn|xyz|
or perl
:
perl -i.bak -ple '$_.="|"' file
Solution 3
With GNU sed
, you could replace the end of line with |
by using:
sed -i 's/$/|/' temp.txt
That will match the end of the line and "replace" it with |
, but of course the line will still end and keep its \n
Related videos on Youtube
Author by
Vicky
A software developer with zeal to learn new things all the time!!
Updated on September 18, 2022Comments
-
Vicky over 1 year
I am using
ksh
.I have a file
temp.txt
with some pipe delimited data.one|two|three|four|five abc|def|pqr|lmn|xyz
As clear from example, the record ends with a new line character after the data value in the last column.
However, I want the record to end with a pipe delimiter and a new line character as below:
one|two|three|four|five| abc|def|pqr|lmn|xyz|
I tried the following commands but still unsuccessful:
tr '\n' '|\n' < temp.txt
and
sed -i 's/\n/|\n/g' temp.txt
Am I missing something?
-
Vicky about 9 yearsGreat. This works. Did not know end-of-line is $ for sed. Thanks!
-
Vicky about 9 yearsGreat. This works. Did not know end-of-line is $ for sed. Thanks!
-
heemayl about 9 years+1. Could you explain the
paste
a bit.. -
cuonglm about 9 years@heemayl:
:
is no-op and it was piped topaste
.paste
merge lines fromfile
and stdin (which is empty) with|
as delimiter. -
Angel Todorov about 9 yearshmm, excessively clever for my taste (and I love a dash of clever!). How about
paste -d'|' file /dev/null
? -
Angel Todorov about 9 yearsThe
$
end-of-line marker is a regular expression feature, not specific to sed. -
cuonglm about 9 years@glennjackman: It's ok in this case, but can cause long typing when you need multiple
/dev/null
, something like this. -
syntaxerror almost 9 yearsMay I also add that the ignoring of
\n
(et al) will even apply to their hexadecimal representation! That means in practice, thatsed 's/someregex\x0a/something/'
will fail as well, becausesed
will ignore the control character specified in hex in the regex. I had to learn this the hard way back then, when I had to debug the actual cause why my parser did not operate the expected way.