Remove carriage return in Unix

后端 未结 21 2218
傲寒
傲寒 2020-11-22 03:40

What is the simplest way to remove all the carriage returns \\r from a file in Unix?

相关标签:
21条回答
  • 2020-11-22 04:08

    cat input.csv | sed 's/\r/\n/g' > output.csv

    worked for me

    0 讨论(0)
  • 2020-11-22 04:09

    sed -i s/\r// <filename> or somesuch; see man sed or the wealth of information available on the web regarding use of sed.

    One thing to point out is the precise meaning of "carriage return" in the above; if you truly mean the single control character "carriage return", then the pattern above is correct. If you meant, more generally, CRLF (carriage return and a line feed, which is how line feeds are implemented under Windows), then you probably want to replace \r\n instead. Bare line feeds (newline) in Linux/Unix are \n.

    0 讨论(0)
  • 2020-11-22 04:09

    Though it's a older post, recently I came across with same problem. As I had all the files to rename inside /tmp/blah_dir/ as each file in this directory had "/r" trailing character ( showing "?" at end of file), so doing it script way was only I could think of.

    I wanted to save final file with same name (without trailing any character). With sed, problem was the output filename which I was needed to mention something else ( which I didn't want).

    I tried other options as suggested here (not considered dos2unix because of some limitations) but didn't work.

    I tried with "awk" finally which worked where I used "\r" as delimiter and taken the first part:

    trick is:

    echo ${filename}|awk -F"\r" '{print $1}'
    

    Below script snippet I used ( where I had all file had "\r" as trailing character at path /tmp/blah_dir/) to fix my issue:

    cd /tmp/blah_dir/
    for i in `ls`
      do
        mv   $i     $(echo $i | awk -F"\r" '{print $1}')
    done
    

    Note: This example is not very exact though close to what I worked (Mentioning here just to give the better idea about what I did)

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