Here is my command line:
$ cat /etc/hosts | ruby -ne 'print $_.gsub(/$/, %q( xxx ))'
it returns:
# To allow the same kube context to work on the host and the container: xxx
xxx 127.0.0.1 localhost kubernetes.docker.internal xxx
xxx # End of section xxx
I did not expect the xxx at the beginning of the line (it does not have it in the first line). I need gsub
because I need to match something else and the end of line in actual code: (something else|$)
, this is just a simplified case to show the expected behavior.
To summarize:
- How do I match the end of line only?
- Why it matches the beginning of line starting from the second line?
Thanks.
CodePudding user response:
$
notes the position at the end of the line, which comes after the \n
at the end of the line! "Replacing" it will essentially add content after the \n
, which makes it show up on the next line. However, replacing $ doesn't make sense, as there will always be a $ in the line. Instead, You want to match the the pattern /\r?\n/
instead.
\r is the escape code for chr 13, the "carriage return", and \n is the escape code for chr 10, the newline character. Unix-like systems will write lines with just the \n, while Windows systems will terminate lines with \r\n, so accounting for both characters is ideal.
Since the matched pattern is replaced, but you still presumably want to keep newlines in the output, we include the matched pattern in the output.
cat /etc/hosts | ruby -ne 'print $_.gsub(/\r?\n/, "xxx\\0")'
Or, you can just replace the newline and use puts
rather than print
to add it back when the line is echoed to stdout:
cat /etc/hosts | ruby -ne 'puts $_.gsub(/\r?\n/, "xxx")'