I have multiple files with the following text:
20~02~19~05-01-52
2249\\\2249\\\2249\\\2249\\\2249\\\2249\\\2248\\\
I'd like to use sed or another Linux command to replace \\\
with a newline.
sed 's|\\\\\\|\n|g' filename
does it, if you're using GNU sed
.
If you want POSIX sed
, then this should work (quite a lot of escaping!):
sed 's|\\\\\\|\
|g' filename
I'd use Perl here since it has more advanced regexes that can easily support repetition. So, something like this:
$ perl -pe 's/\\{3}/\n/g' file
20~02~19~05-01-52
2249
2249
2249
2249
2249
2249
2248
The -pe
means "print each input line after applying the script given by -e to it". The script itself simply replaces every occurrence of exactly 3 \
with a newline. We need \\
instead of \
because the \
needs to be escaped.
If your sed
supports it (GNU sed does) you can use the same approach:
$ sed -E 's/\\{3}/\n/g' file
20~02~19~05-01-52
2249
2249
2249
2249
2249
2249
2248
\\\{3\}
in standard BRE in sed
as well. Actually, the \{x,y\}
BRE operator is more portable than the {x,y}
ERE operator.
Commented
Feb 20, 2020 at 19:00
Using sed: sed -n 's/\\\\\\/\n/g; p' filename.txt
.
It is important to have the 'p' after the semicolon, otherwise it would not print the first line where no substitution takes place. 6 backslashes because 3 backslashes used as escape characters for the 3 backslashes you have. 'g' for global. '-n' to avoid automatic printing.
p
and the first line. If I do the command without -n
and without p
, the output is the same, including the first line, at least with GNU's sed
. Automatic printing does not depend on whether substitutions were made on a line.
-n
and p
options. But usually I work with more complicated problems when using sed and automatic printing only gets in the way. It's normally easier when I always suppress automatic printing and print only when I want to, rather than having to think if this particular problem requires automatic suppression of printing.
p
command come in without the semicolon in between, like this: sed -n 's/\\\\\\/\n/gp' filename.txt
. Or normally I don't want to print a certain range of files, and perform substitutions on the included lines in a file. So in almost all my use cases, I would need to suppress automatic printing, so I developed the habit. Otherwise you're right, don't need it in this particular instance.
Just a different approach, assuming that the file has no other patterns like this, using GNU sed
:
sed -E 's;([0-9]{4}).{3};\1\n;g' < file
I rewrote the code that receives the Serial data and used the following to generate linefeeds. Thank you so much for the posts . This will keep me studying for a while.
sed -i 's/\\n/\n/g' *.txt