Linux / UNIX: Sed Replace Newline

How do I replace newline (\n) with sed under UNIX / Linux operating systems?

You can use the following sed command:

sed '{:q;N;s/\n//g;t q}' /path/to/data.txt

You can replace newline (\n) with * character or word ‘FOO’:

sed '{:q;N;s/\n/*/g;t q}' /path/to/data.txt


sed '{:q;N;s/\n/FOO/g;t q}' /path/to/data.txt

OR replace it with tab (\t):

sed '{:q;N;s/\n/\t/g;t q}' /path/to/data.txt

To update file use -i option:

sed -i '{:q;N;s/\n/\t/g;t q}' /path/to/data.txt

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 4 comments so far... add one

CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one
  • jalal hajigholamali Aug 3, 2011 @ 16:04

    very nice example

  • Claudio Oct 28, 2011 @ 21:25

    It doesnt work for me :(

    $ sed ‘{:q;N;s/\n/\t/g;t q}’ /fi/fa/foo.fu
    sed: 1: “{:q;N;s/\n/\t/g;t q}”: unexpected EOF (pending }’s)

  • Harry Phillips Mar 27, 2013 @ 5:12

    Doesn’t work for me in Cygwin, if there are 17 lines the first line has 16 of the replacement, line 2 will have 15 etc until the last line does not have the replacement.

  • Harry Phillips Mar 27, 2013 @ 5:17

    Simpler way to replace the end of the line:

    sed ‘s/$/FOO/’ /path/to/data.txt

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @