Finding number of lines of a data file using command line - command-line

There is a conventional way to read each line one by one and check iostat hits nonzero or negative value at every reading. However, I would like to call system(command) routine and
use wc -l command to count the number of and then want to allocate the dimension of the array where I want to put the data. For the example, I am printing the number of lines in both ways:
Program Test_reading_lines
integer:: count,ios, whatever
character(LEN=100):: command
Print*,'Reading number of lines in a standard way'
count=0
open (10, file='DATA_FILE')
Do
read (10,*,iostat=ios) whatever
if (ios/=0) exit
count=count+1
End Do
close(10)
Print*,'Number of lines =', count
Print*,'Reading number of lines using shell command'
command='cat DATA_FILE | wc -l'
call system(command)
Print*,'Number of lines =','< ? >'
End Program Test_reading_lines
Unfortunately, in the latter case, can I assign a variable like count as in the standard case? That is, I want to print a variable instead of '< ? >' in the last print command.

This is not possible in a straightforward way. You could redirect the output of the command to a file, then open it and read it http://compgroups.net/comp.lang.fortran/how-to-get-the-output-of-call-system-in-a-v/216294
Or use some even more sophisticated features of the Unix functions and call its C API (see the first answer in that thread).
The EXECUTE_COMMAND_LINE() also does not have any feature to read the output of the command directly.

If you want to use the Unix command $ wc -l, you could call the Fortran subroutine execute_command_line which is common to many Fortran compilers, gfortran included.
Here is a working example which computes the number of lines, nlines, of a file called style.gnuplot and then uses nlines to append some rows to style.gnuplot by overwriting the last one.
PROGRAM numLines
IMPLICIT NONE
integer, parameter :: n = 100
integer :: i, nLines
real, parameter :: x0 = -3.14, xEnd = 3.14
real :: dx
real, dimension (:), allocatable :: x, fun
allocate(x(0:n)) ! Allocate the x array
allocate(fun(0:n)) ! Allocate the fun array
dx = abs(xEnd-x0)/n
x(0:n) = [(x0+i*dx, i = 0,n)] ! Create the x array
fun(0:n) = [(sin(x0+i*dx), i = 0,n)] ! Create the fun array
open(unit=1,file="plotFunction.dat")
DO i=0,size(x)-1
write(1,*) x(i), ' ', fun(i) ! Save the function to a file to plot
END DO
close(unit=1)
deallocate(x) ! Deallocate the x array
deallocate(fun) ! Deallocate the fun array
open(unit=7, file="style.gnuplot")
write(7,*) "set title 'y = sin(x)' font 'times, 24'"
write(7,*) "set tics font 'times, 20'"
write(7,*) "set key font 'times,20'"
write(7,*) "set grid"
write(7,*) "set key spacing 1.5"
write(7,*) "plot '<cat' u 1:2 w l lw 2 linecolor rgb 'orange' notitle "
close(unit=7)
CALL execute_command_line("wc -l style.gnuplot | cut -f1 -d' ' > nlines.file") ! COunt the lines
open(unit=1,file='nlines.file')
read(1,*) nlines ! Here the number of lines is saved to a variable
close(unit=1)
CALL execute_command_line("rm nlines.file") ! Remove nlines.file
CALL execute_command_line("cat plotFunction.dat | gnuplot -p style.gnuplot") ! Show the plot within the executable
open(unit=7,file="style.gnuplot")
DO i = 1,nLines-1
read(7,*) ! Read the file untile the penultimate row,
END DO ! then append the other rows
write(7,*) "set object rectangle at -3.14,0 size char 1, char 1", &
" fillcolor rgb 'blue' fillstyle solid border lt 2 lw 1.5"
write(7,*) "set object rectangle at 0,0 size char 1, char 1", &
" fillcolor rgb 'blue' fillstyle solid border lt 2 lw 1.5"
write(7,*) "set object rectangle at 3.14,0 size char 1, char 1", &
" fillcolor rgb 'blue' fillstyle solid border lt 2 lw 1.5"
write(7,*) "plot 'plotFunction.dat' u 1:2 w l lw 2 linecolor rgb 'orange' notitle"
close(unit=7)
CALL execute_command_line("gnuplot -p 'style.gnuplot'") ! Load again style.gnulot with the appended lines
END PROGRAM numLines
My code might not be elegant, but it seems to work!

Related

character shows up as 'y' instead of a space '

In matlab i'm coding a Ceaser Cipher, but the space shows up as a 'y' character.
How can I replace that with a space
case 4
disp('Breaking Ceaser Cipher')
cs = menu('Please Enter your Choice','Encryption','Decryption');
if cs==1
c = input('Enter the message: ','s');
sh = str2double(input('Enter shift: ','s'));
c=upper(c);
lc=length(c);
for i=1:lc
p(i)=int16(c(i))-65+sh;
end
p=mod(p,26)+97;
p=char(p);
disp( p)
end
end
output example:
Breaking Ceaser Cipher
Enter the message:
my name is jeff
Enter shift:
5
rdysfrjynxyojkk
Here we see that the encryption is correct, but the space is being replaced by 'y'. It does not replace the character 'y' when used as an input, the space bar somehow comes out as a 'y'.
I'v also tried using p2 = regexprep(c, 'y', ' ') in order to replace the 'y' string with space.Also looked into isspace function. No luck
You are halfway there:
spaces=isspace(c)
% make array of spaces
out=blanks(size(c));
% get array without spaces
c=c(~spaces);
% do stuff to c, without spaces.
p=mod(p,26)+97;
p=char(p);
% Fill p in corresponding locations
out(~spaces)=p;

error in debugging the algorithm

I'm trying to make an algorithm in Matlab that scans the character array from left to right and if it encounters a space, it should do nothing, but if it encounters 2 consecutive spaces, it should start printing the remaining quantities of array from next line. for example,
inpuut='a bc d';
after applying this algorithm, the final output should have to be:
a bc
d
but this algorithm is giving me the output as:
a bc
d d
Also, if someone has got a more simpler algorithm to do this task, do help me please :)
m=1; t=1;
inpuut='a bc d';
while(m<=(length(inpuut)))
if((inpuut(m)==' ')&&(inpuut(m+1)==' '))
n=m;
fprintf(inpuut(t:(n-1)));
fprintf('\n');
t=m+2;
end
fprintf(inpuut(t));
if(t<length(inpuut))
t=t+1;
elseif(t==length(inpuut))
t=t-1;
else
end
m=m+1;
end
fprintf('\n');
OK I gave up telling why your code doesn't work. This is a working one.
inpuut='a bc d ';
% remove trailing space
while (inpuut(end)==' ')
inpuut(end)=[];
end
str = regexp(inpuut, ' ', 'split');
for ii = 1:length(str)
fprintf('%s\n', str{ii});
end
regexp with 'split' option splits the string into a cell array, with delimiter defined in the matching expression.
fprintf is capable of handling complicated strings, much more than printing a single string.
You can remove the trailing space before printing, or do it inside the loop (check if the last cell is empty, but it's more costly).
You can use regexprep to replace two consecutive spaces by a line feed:
result_string = regexprep(inpuut, ' ', '\n');
If you need to remove trailing spaces: use this first:
result_string = regexprep(inpuut, ' $', '');
I have a solution without using regex, but I assumed you wanted to print on 2 lines maximum.
Example: with 'a b c hello':
a b
c hello
and not:
a b
c
hello
In any case, here is the code:
inpuut = 'a b c';
while(length(inpuut) > 2)
% Read the next 2 character
first2char = inpuut(1:2);
switch(first2char)
case ' ' % 2 white spaces
% we add a new line and print the rest of the input
fprintf('\n%s', inpuut(3:end));
inpuut = [];
otherwise % not 2 white spaces
% Just print one character
fprintf('%s', inpuut(1))
inpuut(1) = [];
end
end
fprintf('%s\n', inpuut);

How can I use sed to to convert $$ blah $$ in TeX to \begin{equation} blah \end{equation}

I have files with entries of the form:
$$
y = x^2
$$
I'm looking for a way (specifically using sed) to convert them to:
\begin{equation}
y = x^2
\end{equation}
The solution should not rely on the form of the equation (which may also span mutiple lines) nor on the text preceding the opening $$ or following the closing $$.
Thanks for the help.
sed '
/^\$\$$/ {
x
s/begin/&/
t use_end_tag
s/^.*$/\\begin{equation}/
h
b
: use_end_tag
s/^.*$/\\end{equation}/
h
}
'
Explanation:
sed maintains two buffers: the pattern space (pspace) and the hold space (hspace). It operates in cycles, where during each cycle it reads a line and executes the script for that line. pspace is usually auto-printed at the end of each cycle (unless the -n option is used), and then deleted before the next cycle. hspace holds its contents between cycles.
The idea of the script is that whenever $$ is seen, hspace is first checked to see if it contains the word "begin". If it does, then substitute the end tag; otherwise substitute the begin tag. In either case, store the substituted tag in the hold space so it can be checked next time.
sed '
/^\$\$$/ { # if line contains only $$
x # exchange pspace and hspace
s/begin/&/ # see if "begin" was in hspace
t use_end_tag # if it was, goto use_end_tag
s/^.*$/\\begin{equation}/ # replace pspace with \begin{equation}
h # set hspace to contents of pspace
b # start next cycle after auto-printing
: use_end_tag
s/^.*$/\\end{equation}/ # replace pspace with \end{equation}
h # set hspace to contents of pspace
}
'
This might work for you (GNU sed):
sed -r '1{x;s/^/\\begin{equation}\n\\end{equation}/;x};/\$\$/{g;P;s/(.*)\n(.*)/\2\n\1/;h;d}' file
Prime the hold space with the required strings. On encountering the marker print the first line and then swap the strings in anticipation of the next marker.
I can not help you with sed, but this awk should do:
awk '/\$\$/ && !f {$0="\\begin{equation}";f=1} /\$\$/ && f {$0="\\end{equation}";f=0}1' file
\begin{equation}
y = x^2
\end{equation}
The f=0is not needed, if its not repeated.

Matlab - how to remove a line break when printing to screen?

There is for example a big big score
for 2 hours
and there is need to see how many more before the end of
do output on the screen of the outer loop
but the values ​​and there are many, such as 70 000
Question - how to remove a line break when printing to screen
not to receive 70 000 lines
and to see only the current display in one line?
Instead of using disp to display text to the screen, use fprintf, which requires you to enter line breaks manually.
Compare
>> disp('Hello, '), disp('World')
Hello,
World
with
>> fprintf('Hello, '), fprintf('World\n')
Hello, World
The \n at the end of 'World\n' signifies a line break (or newline as they're commonly called).
Try this function, which you can use in place of disp for a string argument. It displays to the command window, and remembers the message it has displayed. When you call it the next time, it first deletes the previous output from the command window (using ASCII backspace characters), then prints the new message.
In this way you only get to see the last message, and the command window doesn't fill up with old messages.
function teleprompt(s)
%TELEPROMPT prints to the command window, over-writing the last message
%
% TELEPROMPT(S)
% TELEPROMPT() % Terminate
%
% Input S is a string.
persistent lastMsg
if isempty(lastMsg)
lastMsg = '';
end
if nargin == 0
lastMsg = [];
fprintf('\n');
return
end
fprintf(repmat('\b', 1, numel(sprintf(lastMsg))));
fprintf(s);
lastMsg = s;

Code Golf - Word Scrambler

Please answer with the shortest possible source code for a program that converts an arbitrary plaintext to its corresponding ciphertext, following the sample input and output I have given below. Bonus points* for the least CPU time or the least amount of memory used.
Example 1:
Plaintext: The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!
Ciphertext: eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos
Example 2:
Plaintext: 123 1234 12345 123456 1234567 12345678 123456789
Ciphertext: 312 4213 53124 642135 7531246 86421357 975312468
Rules:
Punctuation is defined to be included with the word it is closest to.
The center of a word is defined to be ceiling((strlen(word)+1)/2).
Whitespace is ignored (or collapsed).
Odd words move to the right first. Even words move to the left first.
You can think of it as reading every other character backwards (starting from the end of the word), followed by the remaining characters forwards. Corporation => XoXpXrXtXoX => niaorCoprto.
Thank you to those who pointed out the inconsistency in my description. This has lead many of you down the wrong path, which I apologize for. Rule #4 should clear things up.
*Bonus points will only be awarded if Jeff Atwood decides to do so. Since I haven't checked with him, the chances are slim. Sorry.
Python, 50 characters
For input in i:
' '.join(x[::-2]+x[len(x)%2::2]for x in i.split())
Alternate version that handles its own IO:
print ' '.join(x[::-2]+x[len(x)%2::2]for x in raw_input().split())
A total of 66 characters if including whitespace. (Technically, the print could be omitted if running from a command line, since the evaluated value of the code is displayed as output by default.)
Alternate version using reduce:
' '.join(reduce(lambda x,y:y+x[::-1],x) for x in i.split())
59 characters.
Original version (both even and odd go right first) for an input in i:
' '.join(x[::2][::-1]+x[1::2]for x in i.split())
48 characters including whitespace.
Another alternate version which (while slightly longer) is slightly more efficient:
' '.join(x[len(x)%2-2::-2]+x[1::2]for x in i.split())
(53 characters)
J, 58 characters
>,&.>/({~(,~(>:#+:#i.#-#<.,+:#i.#>.)#-:)#<:##)&.><;.2,&' '
Haskell, 64 characters
unwords.map(map snd.sort.zip(zipWith(*)[0..]$cycle[-1,1])).words
Well, okay, 76 if you add in the requisite "import List".
Python - 69 chars
(including whitespace and linebreaks)
This handles all I/O.
for w in raw_input().split():
o=""
for c in w:o=c+o[::-1]
print o,
Perl, 78 characters
For input in $_. If that's not acceptable, add six characters for either $_=<>; or $_=$s; at the beginning. The newline is for readability only.
for(split){$i=length;print substr$_,$i--,1,''while$i-->0;
print"$_ ";}print $/
C, 140 characters
Nicely formatted:
main(c, v)
char **v;
{
for( ; *++v; )
{
char *e = *v + strlen(*v), *x;
for(x = e-1; x >= *v; x -= 2)
putchar(*x);
for(x = *v + (x < *v-1); x < e; x += 2)
putchar(*x);
putchar(' ');
}
}
Compressed:
main(c,v)char**v;{for(;*++v;){char*e=*v+strlen(*v),*x;for(x=e-1;x>=*v;x-=2)putchar(*x);for(x=*v+(x<*v-1);x<e;x+=2)putchar(*x);putchar(32);}}
Lua
130 char function, 147 char functioning program
Lua doesn't get enough love in code golf -- maybe because it's hard to write a short program when you have long keywords like function/end, if/then/end, etc.
First I write the function in a verbose manner with explanations, then I rewrite it as a compressed, standalone function, then I call that function on the single argument specified at the command line.
I had to format the code with <pre></pre> tags because Markdown does a horrible job of formatting Lua.
Technically you could get a smaller running program by inlining the function, but it's more modular this way :)
t = "The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!"
T = t:gsub("%S+", -- for each word in t...
function(w) -- argument: current word in t
W = "" -- initialize new Word
for i = 1,#w do -- iterate over each character in word
c = w:sub(i,i) -- extract current character
-- determine whether letter goes on right or left end
W = (#w % 2 ~= i % 2) and W .. c or c .. W
end
return W -- swap word in t with inverted Word
end)
-- code-golf unit test
assert(T == "eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos")
-- need to assign to a variable and return it,
-- because gsub returns a pair and we only want the first element
f=function(s)c=s:gsub("%S+",function(w)W=""for i=1,#w do c=w:sub(i,i)W=(#w%2~=i%2)and W ..c or c ..W end return W end)return c end
-- 1 2 3 4 5 6 7 8 9 10 11 12 13
--34567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
-- 130 chars, compressed and written as a proper function
print(f(arg[1]))
--34567890123456
-- 16 (+1 whitespace needed) chars to make it a functioning Lua program,
-- operating on command line argument
Output:
$ lua insideout.lua 'The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!'
eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos
I'm still pretty new at Lua so I'd like to see a shorter solution if there is one.
For a minimal cipher on all args to stdin, we can do 111 chars:
for _,w in ipairs(arg)do W=""for i=1,#w do c=w:sub(i,i)W=(#w%2~=i%2)and W ..c or c ..W end io.write(W ..' ')end
But this approach does output a trailing space like some of the other solutions.
For an input in s:
f=lambda t,r="":t and f(t[1:],len(t)&1and t[0]+r or r+t[0])or r
" ".join(map(f,s.split()))
Python, 90 characters including whitespace.
TCL
125 characters
set s set f foreach l {}
$f w [gets stdin] {$s r {}
$f c [split $w {}] {$s r $c[string reverse $r]}
$s l "$l $r"}
puts $l
Bash - 133, assuming input is in $w variable
Pretty
for x in $w; do
z="";
for l in `echo $x|sed 's/\(.\)/ \1/g'`; do
if ((${#z}%2)); then
z=$z$l;
else
z=$l$z;
fi;
done;
echo -n "$z ";
done;
echo
Compressed
for x in $w;do z="";for l in `echo $x|sed 's/\(.\)/ \1/g'`;do if ((${#z}%2));then z=$z$l;else z=$l$z;fi;done;echo -n "$z ";done;echo
Ok, so it outputs a trailing space.