Replace newlines with literal \n

后端 未结 6 1583
北荒
北荒 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:21

    You could do this using sed and tr:

    sed 's/$/\\n/' file | tr -d '\n'
    

    However this will add an extra \n at the end.

    0 讨论(0)
  • 2020-12-05 17:24

    With the -zoption you can do

    sed -z 's/\n/\\n/g' file
    

    or

    sed -z "s/\n/\\\n/g" file
    
    0 讨论(0)
  • 2020-12-05 17:34

    This should work with both LF or CR-LF line endings:

    sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' file
    
    0 讨论(0)
  • 2020-12-05 17:39

    Here is little python script for replacing the '\r\n' with '\r' in directory in a recursive way import os import sys

    if len(sys.argv) < 2:
        print("Wrong arguments. Expected path to directory as arg 1.")
        exit(1)
    
    path = sys.argv[1]
    
    
    def RecOpOnDir(path, op) :
        for f in os.listdir(path):
            full_f = path + "/" + f
            if os.path.isdir(full_f):
                RecOpOnDir(full_f, op)
            else:
                try:
                    op(full_f)
                except Exception as ex:
                    print("Exception during proc '", full_f, "' Exception:", ex)
    
    file_counter = 0
    
    def WinEndingToUnix(path_to_file):
        global file_counter
        file_counter += 1
        file_strs = []
        with open(path_to_file) as f:
            for line in f:
                file_strs.append(line.replace(r"\r\n", r"\n"))
    
        with open(path_to_file, "w") as fw:
            fw.writelines(l for l in file_strs)
    
    try:
        RecOpOnDir(path, WinEndingToUnix)
        print("Completed.", file_counter, "files was reformed")
    except Exception as ex:
        print("Exception occured: ", ex)
        exit(1)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 17:46

    In case it helps anyone, I was searching for the opposite of this question: to replace literal '\'n in a string with newline. I managed to solve it with sed like this:

    _s="foo\nbar\n"
    echo $_s | sed 's/\\n/\n/g'
    
    0 讨论(0)
提交回复
热议问题