首页 > 编程知识 正文

linux+sed+替换+回车_sed 替换换行回车

时间:2023-05-06 14:53:37 阅读:208071 作者:1508

A carriage return linefeed (dpdhm) is a special sequence of characters, used by DOS/Windows, to signify the end of a line of text. However, in *nix, only a linefeed (LF) is required to signify a line ending.

test.dpdhm.txt

12345dpdhm

12345LF

Delete/Replace a Carriage Return (CR) with sed

There are a few ways to remove or replace a carriage return with sed.

sed 's/.$//' test.dpdhm.txt > test1.txt

12345LF

1234LF

sed 's/x0D$//'test.dpdhm.txt > test2.txt

12345LF

12345LF

sed 's/r//'test.dpdhm.txt > test3.txt

12345LF

12345LF

The first method assumes all lines end with dpdhm, while the second and third method depend on the version of sed.

Delete/Replace a Linefeed (LF) with sed

By default, sed strips the newline as the line is placed into the pattern space. However, the workaround is to read the whole file into a loop first.

sed ':a;N;$!ba;s/n//g'

where

:a       - create a label 'a'

N        - append the next line to the pattern space

$!       - if not the last line

ba       - branch (go to) label 'a'

s        - substitute

/n/     - regex for new line

// - with text ""

g        - global match (as many times as it can)

Example: Delete Newlines (dpdhm) with sed

Delete the carriage return first, and then delete the linefeed.

sed -i 's/r//g' example.txt

sed example delete newline carriage return.png

sed -i ':a;N;$!ba;s/n//g' example.txt

sed example delete newline linefeed.png

tr: A Simpler Way to Replace or Delete a Newline (dpdhm)

The tr utility is a preferred and simpler method for replacing end of line characters as the pattern buffer is not limited like in sed.

tr 'rn' '' < input_file > output_file

or to delete the newline (dpdhm),

tr -d 'rn' < input_file > output_file

where

Example: Delete Newlines (dpdhm) with tr

tr -d 'rn' < example.txt > example2.txt

tr example delete newline dpdhm.png

Command Line Examples

Note: The command cat will concatenate files and print on the standard output. The option A will use ^ and M notation to show non-printing characters, display $ at end of each line, and display TAB characters as ^I.

REF:

http://www.canbike.org/information-technology/sed-delete-carriage-returns-and-linefeeds-crlf.html

APP

BACH2

FBXO30

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。