How to merge lines with word between them - merge

If i have 10 lines . between every 2 lines there is word for example (comment)
line1
comment
line2
comment
line3
comment
line4
is there away to merge every 2 lines with the word comment to be like
line1 comment line2
line3 comment line4

Since you haven't mentioned which language you want to do this in, I'm just going to reason about how you want to approach this.
You want to read the first three lines: line1, comment, line2, then add this to your result. You then want to skip the next line comment,
then repeat this process until you run out of lines.
Here it is in JavaScript:
const input = `line1
comment
line2
comment
line3
comment
line4
comment
line5
comment`;
function every2Lines(text) {
const lines = text.split("\n");
const result = [];
// Read four lines
for (let i = 0; i < lines.length; i += 4) {
// Push the three first lines to the result
result.push(lines.slice(i, i + 3).join(" "));
}
return result.join("\n");
}
console.log(input);
console.log();
console.log(every2Lines(input));
Outputs:
line1 comment line2
line3 comment line4
line5 comment

Related

How to increment a text in a file by range with any windows or unix/linux commandline script?

Is there any windows or unix/linux commandline script that can do this?I.e the word "boss" should be incremented from 1 to 60,then 1 to 60 again.
I have a file that contains a list of text like so;
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
.
.
.
I want the output to be:
She is the new boss1
She is the new boss2
She is the new boss3
.
.
.
She is the new boss60
She is the new boss1
She is the new boss2
She is the new boss3
.
.
.
She is the new boss60
.
.
.
So,far I use this perl -i.bak -ape "s/"old-text"/$&.++$A /ge" input.txt && del input.txt.bak to do repeated increment but the output it produces is not what I want.
perl -pe 's/\bboss\b\K/(++$n > 60 ? $n=1 : $n)/eg' file
Word boundaries \b have been added around boss to prevent matching bossy or embossed.
Originally, you used $&.++$A:
The incremented variable needs to be reset conditionally. A ternary ?: expression can be used to achieve that.
$& can be removed by using the PCRE \K escape.
It's easier to not use the save-in-place -i option until you know that the processing being applied is correct.
perl -ple'$_ .= ($. - 1) % 60 + 1'
$. is the current line number.
Specifying file to process to Perl one-liner
This Linux command may do:
i=1 && while read f; do echo "$f$i"; i=$(( i+1 )); done <original_file.txt > new_file.txt
Here is an awk:
$ echo "She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss
She is the new boss" | awk -v max=3 '{cnt>=max ? cnt=1:cnt++; $NF=$NF cnt;} 1'
Prints:
She is the new boss1
She is the new boss2
She is the new boss3
She is the new boss1
She is the new boss2
She is the new boss3
She is the new boss1
She is the new boss2
So just change the input max to 60 and that should work as your example describes.
For a file, just do:
$ awk -v max=60 '{cnt>=max ? cnt=1:cnt++; $NF=$NF cnt;} 1' your_file
I don't think python is clean in this task. But I write this for you.
import re
class LineReplacer(object):
def __init__(self, replace_word, max_word_count):
self.word_index = 1
self.word_to_replace = replace_word
self.max_word_count = max_word_count
#property
def word_regex(self):
return re.compile(f"(?<=[^a-zA-Z0-9]){self.word_to_replace}(?=[^a-zA-Z0-9])")
def replace_function(self, match):
current_index = self.word_index
if self.word_index < self.max_word_count:
self.word_index += 1
else:
self.word_index = 1
return f"{match.group()}{current_index}"
def replace_file(self, input_file_path, output_file_path):
output = open(output_file_path, "w")
with open(input_file_path, "r") as f:
for line in f.readlines():
new_line = self.word_regex.sub(self.replace_function, line)
output.write(new_line)
output.close()
if __name__ == "__main__":
replacer = LineReplacer("boss", 60)
replacer.replace_file("test.txt", "output.txt")
This will generate a new file.

Ghostscript ps2pdf not Working Correctly from MATLAB

I have a .tex file I am attempting to write from a MATLAB environment (2017b) using first latex, then dvips, and finally ps2pdf to create the PDF file. The PDF file is properly created when I run it through TeXWorks, but sends an error from ps2pdf when I try to run it through. I'm not entirely sure what's wrong with the way I send it to the command line. Here is the script I am attempting to run.
set(groot, 'defaultAxesTickLabelInterpreter','latex');
set(groot, 'defaultLegendInterpreter','latex');
set(0,'defaultTextInterpreter','latex');
addpath('C:\Program Files (x86)\MiKTeX\miktex\bin\x64')
exampledir='\\our\server\';
examplefilename='test';
texdoc=fullfile(exampledir,strcat(examplefilename,'.tex'));
auxdoc=fullfile(exampledir,strcat(examplefilename,'.aux'));
logdoc=fullfile(exampledir,strcat(examplefilename,'.log'));
dvidoc=fullfile(exampledir,strcat(examplefilename,'.dvi'));
psdoc=fullfile(exampledir,strcat(examplefilename,'.ps'));
pdfdoc=fullfile(exampledir,strcat(examplefilename,'.pdf'));
fileID = fopen(texdoc,'w');
textext=['\documentclass[twoside]{article} %Two-sided document. Required for fancyhf left and right page numbering scheme current.' newline ...
'\usepackage{graphicx}' newline ...
newline ...
'\usepackage{fancyhdr} %Use the package fancy header/footer' newline ...
newline ...
'\usepackage[letterpaper,margin=0.5in,bottom=0.75in,top=0.7in]{geometry} %Ensure the paper is letterpaper.' newline ...
'\usepackage{grffile}' newline ...
'\usepackage{caption}' newline ...
'\usepackage{float} %Float used to position graphics.' newline ...
'\usepackage{lastpage209} %For last page' newline ...
newline ...
'\DeclareGraphicsExtensions{.PDF,.jpg} %Notify LaTeX what type of graphics extensions to expect.' newline ...
newline ...
'\renewcommand{\headrulewidth}{0pt} % remove the header rule' newline ...
newline ...
'\fancyhf{} % clear all header and footers' newline ...
newline ...
'\pagestyle{fancy} %Use the fancy pagestyle, which will include the fancy header and footer options we defined above.' newline ...
newline ...
'\setlength\headheight{38pt} ' newline ...
newline ...
'\fancyhead[L]{{Page \thepage} of \pageref{LastPage}} %Left side on even pages; right side on odd pages.' newline ...
'\fancyhead[R]{\includegraphics[trim={0.3in 0.26in 0.05in 0.26in},clip,width=0.4in]{{\\our\server\mypicture}}}' newline ...
newline ...
'\begin{document} %This will be the actual document and what goes into it.' newline ...
newline ...
'\begin{figure}[h] %Make a figure...' newline ...
newline ...
' \includegraphics[trim={0.25in 0 0 0},clip,width=7.5in]{{\\our\server\mypicture}}' newline ...
newline ...
' \captionsetup{labelformat=empty}' newline ...
newline ...
'\end{figure}' newline ...
newline ...
'\end{document}'];
fprintf(fileID,'%s',textext);
fclose(fileID);
% latex dvips ps2pdf
% text.tex -------> text.dvi -------> text.ps --------> text.pdf
[~,cmdoutlatex] = system(['latex.exe -interaction=nonstopmode -output-directory ' exampledir '\ ' texdoc]);
if contains(cmdoutlatex,'Sorry, but latex.exe did not succeed.')
%Do some kind of check and fix things.
end
[~,cmdoutdvips] = system(['dvips.exe -q* -o ' psdoc ' ' dvidoc]);
if contains(cmdoutdvips,'!')
%Do some kind of check and fix things.
error(['Error: ' cmdoutdvips])
end
[~,cmdoutps2pdf] = system(['ps2pdf ' psdoc ' ' pdfdoc ' -sDEVICE=pdfwrite']);
if contains(cmdoutps2pdf,'Error','IgnoreCase',true)
%Do some kind of check and fix things.
error(cmdoutps2pdf)
end
Per #Cris Luengo's suggestion of moving to pdflatex rather than using latex/dvips/ps2pdf commands, this worked. Here is the sample code of what worked for a system command.
[~,pdflatexout] = system(['pdflatex.exe -output-directory ' strrep(exampledir,'\','/') ' ' texdoc]);
%Check for errors.
if contains(pdflatexout,'Sorry, but pdflatex.exe did not succeed.') || ...
contains(pdflatexout,'error','IgnoreCase',true)
%Deliver the error code.
error(pdflatexout)
end
I placed this after fclose(fileID) in the original code and deleted all that had originally come after that line.

How to replace several lines but not the last

I need to remove lines from word "WORDA" to the last "}" before WORDB.
But there are other "}" before. So SED missed the selection.
...
WORDA
{
blah
{
blahblah
...
blahblahblah
}
}
WORDB 0
...
So I'm trying to replace from "WORDA" to "WORDB" with "WORDB" but I lose the "0" at the end... The result is not inserted... All the last line is replaced.
(Of course, this "0" value can be any other number.)
sed.exe -i /WORDA/,/WORDB/c\WORDB\ file
result
...
WORDB
...
but I need:
...
WORDB 0
...
Any idea?
Crude but effective:
sed '/WORDA/,/WORDB/{/WORDB/!d;}' filename

Awk to generate a file of 100 lines using 5 lines supplied based on some condition

I have a file with 5 lines in it. I'd like to copy and paste these lines until a condition is satisfied.. e.g.,
123 89.98 34.56
AbcDef
0.0 10.567
Hijkl
XYZ 345
I'd like to repeat these lines 20 times and each time incrementing the number '123' (on the fist line) by 1. i.e.,
123 89.98 34.56
AbcDef
0.0 10.567
Hijkl
XYZ 345
124 89.98 34.56
AbcDef
0.0 10.567
Hijkl
XYZ 345
.....
.....
172 89.98 34.56
AbcDef
0.0 10.567
Hijkl
XYZ 345
Is this possible?
One way to do it (but without any elegance) is this:
1) Get a file with the desired final number of lines (in your case, 20x5). Let's name it "100lines.txt".
2) Do:
awk '{if(NR%5==1) {print (NR+4)/5+122, "89.98 34.56"} if(NR%5==2) {print "AbcDef"} if(NR%5==3) {print "0.0 10.567"} if(NR%5==4) {print "Hijkl"} if(NR%5==0) {print "XYZ 345"}}' 100lines.txt
I think it could work.

ANTLR: loop did not match anything at input

sorry for my english! I have problem, faced here with such a problem, give the decision:
line 1:0 required (...)+ loop did not match anything at input < E O F
>
This my file, calc.g
grammar calc;
options {
language = Java;
}
rule: statement+;
statement
: expr NEWLINE
| ID '=' expr NEWLINE
| NEWLINE
;
NEWLINE : '\r'? '\n'
;
expr
: multExpression ('+' multExpression |'-' multExpression)*
;
multExpression
: a1=atom ('*' a2=atom | '/' a2=atom)*
;
atom
: ID
| INT
| '(' expr ')'
;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
INT : ('1'..'9') ('0'..'9')*
;
this is my main:
ANTLRReaderStream input = new ANTLRReaderStream();
calcLexer lexer = new calcLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
calcParser parser = new calcParser(tokens);
parser.rule();
It looks like your input is empty: the parser immediately encounters the EOF (end-of-file) where it expects at least one statement.
Try something like this:
ANTLRStringStream input = new ANTLRStringStream("2*42\n");
calcLexer lexer = new calcLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
calcParser parser = new calcParser(tokens);
parser.rule();
As 280Z28 mentioned in the comment beneath my answer, you should probably force the parser to consume the entire input by adding EOF at the end of your parser's entry point:
rule: statement+ EOF;
and if you want to allow an empty string to be valid input too, change the + to a *;
rule: statement* EOF;
I didn't test it but think you have to add the default EOF token to your grammar:
rule: statement+ EOF!;
Your parser seems to recognize the whole input but at the end there is an EOF but you did not add the corresponding rule to your grammar.