How to remove line breaks from a file in Java?
You need to set text
to the results of text.replace()
:
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");
This is necessary because Strings are immutable -- calling replace
doesn't change the original String, it returns a new one that's been changed. If you don't assign the result to text
, then that new String is lost and garbage collected.
As for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator")
.
How to remove new line characters from a string?
I like to use regular expressions. In this case you could do:
string replacement = Regex.Replace(s, @"\t|\n|\r", "");
Regular expressions aren't as popular in the .NET world as they are in the dynamic languages, but they provide a lot of power to manipulate strings.
How to remove all line breaks from a string
Line breaks (better: newlines) can be one of Carriage Return (CR, \r
, on older Macs), Line Feed (LF, \n
, on Unices incl. Linux) or CR followed by LF (\r\n
, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)
Therefore, the most efficient RegExp
literal to match all variants is
/\r?\n|\r/
If you want to match all newlines in a string, use a global match,
/\r?\n|\r/g
respectively. Then proceed with the replace
method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)
How can I remove a newline character in a string in python
Are you sure it's '\n'
character and not '\\n'
two character sequence? If it's '\n', x.rstrip()
should work. Otherwise, try x.replace('\\n','')
Remove all line breaks from a long string of text
How do you enter line breaks with raw_input
? But, once you have a string with some characters in it you want to get rid of, just replace
them.
>>> mystr = raw_input('please enter string: ')
please enter string: hello world, how do i enter line breaks?
>>> # pressing enter didn't work...
...
>>> mystr
'hello world, how do i enter line breaks?'
>>> mystr.replace(' ', '')
'helloworld,howdoienterlinebreaks?'
>>>
In the example above, I replaced all spaces. The string '\n'
represents newlines. And \r
represents carriage returns (if you're on windows, you might be getting these and a second replace
will handle them for you!).
basically:
# you probably want to use a space ' ' to replace `\n`
mystring = mystring.replace('\n', ' ').replace('\r', '')
Note also, that it is a bad idea to call your variable string
, as this shadows the module string
. Another name I'd avoid but would love to use sometimes: file
. For the same reason.
Remove all newlines from inside a string
strip
only removes characters from the beginning and end of a string. You want to use replace
:
str2 = str.replace("\n", "")
re.sub('\s{2,}', ' ', str) # To remove more than one space
Remove New Lines From String Without Removing \n?
you could print it as a real string
this is done with the letter r
example 1:
print(r"You can use \n to print a new line.")
# You can use \n to print a new line.
this will not remove it, but make it visible as you want in the output
example 2:
text = r"You can use \n to print a new line."
print(text)
# You can use \n to print a new line.
How to remove a newline from a string in Bash
Under bash, there are some bashisms:
The tr
command could be replaced by //
bashism:
COMMAND=$'\nREBOOT\r \n'
echo "|${COMMAND}|"
|
OOT
|
echo "|${COMMAND//[$'\t\r\n']}|"
|REBOOT |
echo "|${COMMAND//[$'\t\r\n ']}|"
|REBOOT|
See Parameter Expansion and QUOTING in bash's man page:
man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash
man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash
Further...
As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND
do contain spaces...
COMMAND=$' \n RE BOOT \r \n'
echo "|$COMMAND|"
|
BOOT
|
CLEANED=${COMMAND//[$'\t\r\n']}
echo "|$CLEANED|"
| RE BOOT |
shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}
CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
| RE BOOT|
CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|
Shortly:
COMMAND=$' \n RE BOOT \r \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|
Note: bash have extglob
option to be enabled (shopt -s extglob
) in order to use *(...)
syntax.
Is there a way to remove a newline character within a string in an array?
You could for example split, remove all the empty entries, and then trim each item to also remove all the leading and trailing whitespace characters including the newlines.
Note that you don't have to escape the space and the hyphen.
const input = `- foo
- bar`;
const chunks = input.split(/ ?- ?/)
.filter(Boolean)
.map(s => s.trim());
console.log(chunks);
Related Topics
How to Parse Very Huge Xml Files in C#
Dataview.Sort - More Than Just Asc/Desc (Need Custom Sort)
Use of "This" Keyword in Formal Parameters for Static Methods in C#
Winforms: Application.Exit VS Environment.Exit VS Form.Close
How to Handle Add to List Event
How to Find One Image Inside of Another
How to Print Webview Content in a Windows Store App
Revisiting Task.Configureawait(Continueoncapturedcontext: False)
Loop Through All Controls of a Form, Even Those in Groupboxes
Measure a String Without Using a Graphics Object
Using Dataannotations with Entity Framework
How to Pass Values Between Forms in C# Windows Application
Internal VS. Private Access Modifiers
Converting Xml to a Dynamic C# Object
Visual Studio One Project with Several Dlls as Output