tr command - how to replace the string “\n” with an actual newline (\n)

后端 未结 2 1267
一向
一向 2020-12-29 18:05

I would like to use the tr command to replace all occurrences of the string \"\\n\" with a new line (\\n).

I tried tr \'\\\\n\' \'\\n\' but

相关标签:
2条回答
  • 2020-12-29 18:45

    Here's how to do it with sed:

    sed 's/\\n/\n/g'
    

    Example usage:

    To replace all occurrences of \n in a file in-place:

    sed -i 's/\\n/\n/g' input_filename
    

    To replace all occurrences of \n through a pipe, and save into another file

    cat file1 file2 file3 file4 | sed 's/\\n/\n/g' > output_file
    
    0 讨论(0)
  • 2020-12-29 18:50

    The Perl solution is similar to the sed solution from sampson-chen:

    perl -pe 's/\\n/\n/g'
    

    Examples:

    Input file with literal \n (not newlines):

    $ cat test1.txt          
    foo\nbar\n\nbaz
    

    Replace literal all occurrences of \n with actual newlines, print into STDOUT:

    $ perl -pe 's/\\n/\n/g' test1.txt
    foo
    bar
    
    baz
    

    Same, change the input file in-place,saving the backup into test1.txt.bak:

    $ perl -i.bak -pe 's/\\n/\n/g' test1.txt
    

    The Perl one-liner uses these command line flags:
    -e : Tells Perl to look for code in-line, instead of in a file.
    -p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.
    -i.bak : Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak.

    SEE ALSO:
    perldoc perlrun: how to execute the Perl interpreter: command line switches
    perldoc perlre: Perl regular expressions (regexes)

    0 讨论(0)
提交回复
热议问题