Replace newlines with literal \n

后端 未结 6 1584
北荒
北荒 2020-12-05 17:17

This stackoverflow question has an answer to replace newlines with sed, using the format sed \':a;N;$!ba;s/\\n/ /g\'.

This works, but not for special characters like

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 17:46

    Is this all you're trying to do?

    $ cat file
    a
    b
    c
    
    $ awk '{printf "%s\\n", $0}' file
    a\nb\nc\n$
    

    or even:

    $ awk -v ORS='\\n' '1' file
    a\nb\nc\n$
    

    Run dos2unix on the input file first to strip the \rs if you like, or use -v RS='\r?\n' with GNU awk or do sub(/\r$/,""); before the printf or any other of a dozen or so clear, simple ways to handle it.

    sed is for simple substitutions on individual lines, that is all. For anything else you should be using awk.

提交回复
热议问题