MySQL Removing trailing linebreaks from a column

后端 未结 6 2040
夕颜
夕颜 2021-01-05 15:29

I want to remove trailing line breaks from my MySQL column. trim() only removes whitespaces but I also want to remove trailing linebreaks. Could anyone suggest?

相关标签:
6条回答
  • 2021-01-05 15:37

    Just ran into this problem, and took care of it like this.

    UPDATE table_name SET col_name = REPLACE(TRIM(TRAILING ' ' FROM col_name), 
                                             TRIM(TRAILING '\r' FROM col_name), 
                                             TRIM(TRAILING '\n' FROM col_name))
    

    This will remove new lines (\n), carriage returns (\r), and whitespace.

    0 讨论(0)
  • 2021-01-05 15:46

    Try something like this:

    REPLACE(FIELD,'\r\n',' ')
    
    0 讨论(0)
  • 2021-01-05 15:47

    You can replace these directly from SQL by matching "\r" at the end, then replacing that "\r".

    Example:

    UPDATE Person SET firstName = REPLACE(firstName, '\n', '')
    where firstName LIKE '%\n'
    

    or

    UPDATE Person SET firstName = REPLACE(firstName, '\r', '')
    where firstName LIKE '%\r'
    
    0 讨论(0)
  • 2021-01-05 15:49

    Another vote for Wallack's idea, but more specifically:

    Update YOURTABLENAME set YOURCOLUMNNAME = replace(YOURCOLUMNNAME, '\r\n','')
    

    Essentially this should replace carriage returns and breaks with nothing.

    Good luck.

    0 讨论(0)
  • 2021-01-05 15:54

    This will remove all escape characters:

    TRIM(TRAILING '\\' FROM (REPLACE(REPLACE(REPLACE(column_name, '\n', ' '), '\r', ' '), '\\', ' ')))
    
    0 讨论(0)
  • 2021-01-05 15:56

    Based on EternalHour's answer:

    UPDATE TABLE_NAME SET `COLUMN_NAME` = TRIM(TRIM(TRAILING '\r' FROM TRIM(TRAILING '\n' FROM TRIM(`COLUMN_NAME`))))
    

    this one removes trailing \r\n one by one, so either it is a newline or a carriage return or both, it will be stripped, and also removes whitespaces before and after the process.

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