I would like to remove all the newline character that occurs after a partiular string and replace it with a tab space. Say for instance my sample.txt is as follows
This might work for you:
echo -e "foo\nbar bar bar bar some text"| sed '/foo$/{N;s/\n/\t/}'
foo bar bar bar bar some text
Actually:
echo -e "foo\nbar bar bar bar some text"| sed '/foo$/N;s/\n/\t/'
foo bar bar bar bar some text
The latter solution is less efficient but not by much!
Mmm. not sure this fits your requirements, but I'd do this in vim:
:g/^foo$/join
Or, if foo could be anywhere on a line:
:g/foo$/join
Of course, :%s/foo\n/foo\t/g
will do nicely too
The sed
version looks like
#!/bin/sed -f
/foo/{
N
s/\n/\t/
}
If this is all you want to do in your sed command, you can simplify the above to a one-liner:
sed -e '/foo/N;y/\n/\t/' <sample.txt
Explanation: N
appends a newline and the next line of input; y/\n/\t
replaces all newlines with tabs, or s/\n/\t/
replaces the first newline with a tab.
Note that since sed
is line-oriented, the newlines in the input are considered line-separators rather than as part of any line (this is in contrast e.g. to Perl).
Not all tools can do newline replacement. Perl can:
cat file.txt | perl -p -e 's/\n/ /g'
perl -pe 's/(?<=foo)\n/\t/' input
Here is how:
cat input.txt | sed ':a;N;$!ba;s/foo\n/foo\t/g'
More about why simple sed 's/foo\n/foo\t/g'
does not work here: http://linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq5_009.html