Menu
  • HOME
  • TAGS

Running executable files using Haskell

Tag: shell,haskell,command-line-arguments,executable

Say there's a C++ code that I've compiled into an executable using:

g++ test.cpp -o testcpp

I can run this using Terminal (I'm using OS X), and provide an input file for processing inside the C++ program, like:

./testcpp < input.txt

I was wondering if doing this is possible, from within Haskell. I have heard about the readProcess function in System.Process module. But that only allows for running system shell commands.

Doing this:

out <- readProcess "testcpp" [] "test.in"

or:

out <- readProcess "testcpp < test.in" [] ""

or:

out <- readProcess "./testcpp < test.in" [] ""

throws out this error (or something very similar depending on which one of the above I use):

testcpp: readProcess: runInteractiveProcess: exec: does not exist (No such file or directory)

So my question is, whether doing this is possible from Haskell. If so, how and which modules/functions should I use? Thanks.

EDIT

Ok, so as David suggested, I removed the input arguments and tried running it. Doing this worked:

out <- readProcess "./testcpp" [] ""

But I'm still stuck with providing the input.

Best How To :

The documentation for readProcess says:

readProcess
  :: FilePath   Filename of the executable (see RawCommand for details)
  -> [String]   any arguments
  -> String     standard input
  -> IO String  stdout

When it's asking for standard input it's not asking for a file to read the input from, but the actual contents of standard input for the file.

So you'll need to use readFile or the like to get the contents of test.in:

input <- readFile "test.in"
out <- readProcess "./testcpp" [] input

Multiple line search in a file using java or unix command

java,shell,unix,command

You can find like this. File file = new File("data/pattern.txt"); Pattern pat = Pattern.compile("subclass \"Pool1\" 11:22:33:44:55:66 \\{\\s*dynamic;\\s*\\}"); String content = Files.lines(file.toPath()).collect(Collectors.joining("\n")); Matcher m = pat.matcher(content); while (m.find()) { System.out.printf("found at %d-%d%n", m.start(), m.end()); } ...

Haskell - generate and use the same random list

haskell,random

Here is a simple example (@luqui mentioned) you should be able to generalize to your need: module Main where import Control.Monad (replicateM) import System.Random (randomRIO) main :: IO () main = do randomList <- randomInts 10 (1,6) print randomList let s = myFunUsingRandomList randomList print s myFunUsingRandomList :: [Int] ->...

AWK write to new column base on if else of other column

linux,bash,shell,awk,sed

You can use: awk -F, 'NR>1 {$0 = $0 FS (($4 >= 0.7) ? 1 : 0)} 1' test_file.csv ...

Identifying when a file is changed- Bash

bash,shell,unix

I would store the output of find, and if non-empty, echo the line break: found=$(find . -name "${myarray[i]}") if [[ -n $found ]]; then { echo "$found"; echo "<br>"; } >> "$tmp" fi ...

How do I silence the HEAD of a curl request while using the silent flag?

bash,shell,curl,command-line,pipe

Try this: curl --silent "www.site.com" > file.txt ...

Haskell do clause with multiple monad types

haskell,monads

A do block is for a specific type of monad, you can't just change the type in the middle. You can either transform the action or you can nest it inside the do. Most times transformations will be ready for you. You can, for instance have a nested do that...

Haskell: When declaring a class, how can I use a type variable that is not immediately in the constructors?

haskell

using TypeFamilies The problem is that you somehow have to connect b with your collection (the elements in it) - there are several ways to do this but I think a rather nice one is using TypeFamilies: {-# LANGUAGE TypeFamilies #-} module Test where import qualified Data.Map as Map import...

How to extract first letters of dashed separated words in a bash variable?

linux,string,bash,shell,variables

This isn't the shortest method, but it doesn't require any external processes. IFS=- read -a words <<< $MY_TEXT for word in "${words[@]}"; do MY_INITIALS+=${word:0:1}; done ...

Combining Event and an attribute in threepenny-gui

haskell,threepenny-gui

This is intentional: The UI.checkedChange event only triggers when the user clicks the checkbox, but not when it is set programmatically. The intention is that the bBool behavior represents the canonical state of the checkbox and the UI.checkedChange event represents request from the user to change it, which may or...

shell script cut from variables

bash,shell,shellcode

With GNU grep: grep -oP 'aaa&\K.*' file Output: 123 456 \K: ignore everything before pattern matching and ignore pattern itself From man grep: -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -P, --perl-regexp Interpret PATTERN as a...

linux - running a process and tailing a file simultaneously

bash,shell,tail

I would simply start the tail in background and the python process in foreground. When the python process finishes you can kill the tail, like this: #!/bin/bash touch /tmp/out # Make sure that the file exists tail -f /tmp/out & pid=$! python test.py kill "$pid" ...

How to replace newlines/linebreaks with a single space, but only if they are inside of start/end regexes?

regex,linux,shell,unix,replace

You can do it using awk as: awk '/\[x/{f=1} {if(f)printf "%s",$0; else print $0;} /y\]/{print ""; f=0}' Output: [x data1 data2 data3 data4 y] [a data5 data 6 data7 data 8 b> [x data y] You can also simplify to: awk '/\[x/,/y\]/{ORS=""; if(/y\]/) ORS="\n";}{print}' Output: [x data1 data2 data3 data4...

Check for decimal point and add it at the end if its not there using awk/perl

regex,perl,shell,awk

In awk Just sub for those fields awk -F, -vOFS="," '{sub(/^[^\.]+$/,"&.",$6);sub(/^[^\.]+$/,"&.",$11)}1' file or sed sed 's/^\(\([^,]*,\)\{5\}[^.,]\+\),/\1./;s/^\(\([^,]*,\)\{10\}[^.,]\+\),/\1./' file ...

Linux-wget command

linux,shell,wget

Try this to create a string variable n, with no leading whitespace (thanks @011c): n="10.0.0.135.527" wget http://infamvn:8081/nexus/content/groups/LDM_REPO_LIN64/com/infa/com.infa.products.ldm.ingestion.server.scala/"$n"-SNAPSHOT/com.infa.products.ldm.ingestion.server.scala-"$n"-20150622.210643-1-sources.jar ...

how to spy on linux binaries for testing of shell scripts

linux,bash,shell,testing,spy

Just an idea, I didn't see this anywhere but: Unless you're using full paths to invoke those binaries, you could create mocks of those libraries, e.g., in your projects bin/ directory and make that directory be the first in your $PATH. export PATH="$PWD/bin:$PATH" To mock grep, for example, you could...

using sed to replace a line with back slashes in a shell script

regex,bash,shell,ssh,sed

You can use it with ssh and heredoc like this: ssh -t -t [email protected]<<'EOF' sed 's~out_prefix=orderid ^2\\\\d\\+ updatemtnotif/~out_prefix=orderid ^2\\\\d\\+ updatemtnotif_fr/~' ~/path/to/file exit EOF PS: It is important to quote the 'EOF' as shown....

Shell script to loop over files with same names but different extensions

linux,bash,shell

anubhava's solution is excellent if, as they do in your example, the extensions sort into the right order. For the more general case, where sorting cannot be relied upon, we can specify the argument order explicitly: for f in *.ext1 do program "$f" "${f%.ext1}.ext2" done This will work even if...

how to deletes line from a text file that are taken from another file [duplicate]

shell,awk,sed,grep,sh

Something like this with grep: grep -vxf lines.txt data.txt > no_dupplicate_lines.txt Sample: AMD$ cat lines.txt Line2 Line4 AMD$ cat data.txt Line1 Line2 Line3 Line4 Line5 AMD$ grep -vxf lines.txt data.txt Line1 Line3 Line5 Print the lines that are not matching (-v) the exact lines (-x) from the file lines.txt (-f...

First three items of a list in Haskell

haskell

Well, foo (x:y:z:xs) plus a “too short clause” certainly wouldn't be a bad solution. Another would be foo xs = case splitAt 3 xs of ([x,y,z],xs') -> calc x y z : foo (y:z:xs') _ -> [] Or, perhaps nicest, import Data.List (tails) foo xs = [ calc x y...

How to “wrap” monadic return value

haskell,monads

createNotificationIdentifierItem :: APNSIdentifier -> APNSItem createNotificationIdentifierItem (Identifier identifier) = Item $ do putWord8 3 putWord16be 4 putWord32be identifier or createNotificationIdentifierItem :: APNSIdentifier -> APNSItem createNotificationIdentifierItem (Identifier identifier) = do Item $ putWord8 3 Item $ putWord16be 4 Item $ putWord32be identifier after making APNSItem an instance of Monad (you can...

Use Unix Executable File to Run Shell Script and MPKG File

osx,shell,unix

The most common issue when handling variables containing paths of directories and files is the presence of special characters such as spaces. To handle those correctly, you should always quote the variables, using double quotes. Better code would therefor be: sudo sh "$path/join.sh" sudo sh "$path/join2.sh" It is also advised...

How does Frege generalize number literals?

haskell,frege

Simple decimal literals without type indicator (i.e. one of the letters lndf) do not automatically have type Int in Frege. They will get assigned the type you probably wanted, and the literal will get adapted accordingly. This is why they are called DWIM (do what I mean) literals. This is...

Missing one condition to display a string

shell

The 'grep' command uses a regular expression to match text. Use a '^' before the expression, to match from the start of the line. So, you can change the line name=$(echo $hello | cut -d' ' -f9 | grep $1) to name=$(echo $hello | cut -d' ' -f9 | grep...

How to extract single-/multiline regex-matching items from an unpredictably formatted file and put each one in a single line into output file?

linux,shell,unix,replace,grep

Assuming that your document is well-formed, i.e. <b> opening tags always match with a </b> closing tag, then this may be what you need: sed '[email protected]<[/]\?b>@\n&\[email protected]' path/to/input.txt | awk 'BEGIN {buf=""} /<b>/ {Y=1; buf=""} /<\/b>/ {Y=0; print buf"</b>"} Y {buf = buf$0} ' | tr -s ' ' Output: <b>data1</b>...

Get each fibbonacci value in haskell

haskell,fibonacci

Consider the simpler problem of summing the first 100 positive integers: sum [x | x <- [1,2..], x <= 100] This doesn't work either. As a human, you know that once x <= 100 returns False, it will never return True again, because x is getting larger. But Haskell doesn't...

Replace all [ ] with {} - as short as possible [on hold]

haskell

All you need is love and to split print into putStrLn . show and then add a simple map in-between which does the conversion: main :: IO () main = let fn '[' = '{' fn ']' = '}' fn c = c in (readLn :: IO [Integer]) >>= putStrLn...

Best practice for handling data types from 3rd party libraries in Haskell?

haskell,types

I am not ready to give a nice list of best practises, but for starters if you want to keep stuff sanely organized, use explicit exports instead of just exporting everything, e.g: module Parser ( parseConfig ) where ... Explicit exports also allow you to reexport your imports, e.g. module...

How to test if a command is a shell reserved word?

bash,shell

#!/bin/bash string=$1 if [[ $(type "$string" 2>&1) == "$string is a shell"* ]]; then echo "Keyword $string is reserved by shell" fi ...

Stopping condition on a recursive function - Haskell

string,function,haskell,if-statement,recursion

Your code doesn't handle the case where a line is shorter than the maximum length. This is somewhat obscured by another bug: n is decremented until a whitespace is found, and then f is called recursively passing this decremented value of n, effectively limiting all subsequent lines to the length...

Haskell return lazy string from file IO

haskell,file-io,lazy-evaluation

You're right, this is a pain. Avoid using the old standard file IO module, for this reason – except to simply read an entire file that won't change, as you did; this can be done just fine with readFile. readCsvContents :: Filepath -> IO String readCsvContents fileName = do contents...

shell script to shutdown/restart Linux system

linux,shell

Yes, use the -S switch which reads the password from STDIN: $echo <password> | sudo -S <command> Exposing your password is generally bad idea search for something that can protect / hide it. In the past I've used Jenkins plugins to do this while executing the scripts regularly....

How can I express foldr in terms of foldMap for type-aligned sequences?

haskell,types,monoids,type-variables,foldable

I found that this typechecks: {-# LANGUAGE RankNTypes #-} module FoldableTA where import Control.Category import Prelude hiding (id, (.)) class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b d -> h b d foldrTA ::...

How do I avoid writing this type of Haskell boilerplate code

haskell,boilerplate

I assume that we'd like to have a solution for the general case where the changing type parameter is not necessarily in the right position for DeriveFunctor. We can distinguish two cases. In the simple case out data type is not recursive. Here, prisms are a fitting solution: {-# LANGUAGE...

Decremented value called in the recursion in Haskell

string,function,haskell,recursion,parameters

Yes, once you call again f with a new value of n, it has no way to reference the old value of n unless you pass it explicitly. One way to do it is to have an internal recursive function with its width parameter, as you have, but that can...

oh-my-zsh error after upgrade: ~/.oh-my-zsh/lib/misc.zsh:3: parse error near `then'

shell,zsh,zshrc,oh-my-zsh

Use upgrade_oh_my_zsh upgrade to the latest version. This issue fix here...

Haskell IO - read from standard input directly to list

haskell

You may write: main = readLn >>= print . subsequences You will need to nail down the type to be read, for example by having a monomorphic subsequences or by annotating readLn. In ghci: Data.List> (readLn :: IO [Integer]) >>= print . subsequences [1,2,3] [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] (I typed in the first...

find numbers divisible by 3 in csv file using shell script

bash,shell,unix,awk

awk -F'|' '{for(i=1;i<=NF;i++)if(!($i%3))print $i}' file this awk one-liner shoud do. With your example, the cmd outputs: 3 6 9 ...

Mac OSX - Allow for user input in shell script via GUI or Prompt

osx,bash,shell

From what I understand I would recommend you look in to Applescript as this will allow you to have a GUI Interface as well as executing 'SHELL' commands. First of all I would open 'Script Editor' program that comes preinstalled on Mac's This is an example script which asks for...

Matching string inside file and returning result

regex,string,bash,shell,grep

Using sqlite3 from bash on OS X seems fairly straightforward (I'm no expert at this, by the way). You will need to find out which table you need. You can do this with an interactive session. I'll show you with the database you suggested: /Users/fredbloggs> sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db SQLite version...

Using the shell provided with NodeJS

javascript,node.js,shell,require,node-modules

As per issue #5431, looks like the Node.JS REPL doesn't find globally-installed modules and this is expected behaviour. In the article linked from that issue, it reads: If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your...

Why can I view some Unix executable files in Mac OS X and not others?

git,bash,shell,unix,binary

Executable files may be scripts (in which case you can read the text), or binaries (which are ELF formatted machine code). Your shell script is a script; git is an ELF binary. You can use the file command to see more detail. For example, on my nearest Linux system: $...

Delete some lines from text using Linux command

linux,shell,sed,grep,pattern-matching

The -v option to grep inverts the search, reporting only the lines that don't match the pattern. Since you know how to use grep to find the lines to be deleted, using grep -v and the same pattern will give you all the lines to be kept. You can write...

apply a transformation with function inline

haskell

The read lambda applies to the first argument and the first argument to the function given to foldl is the accumulator. Those two arguments are the opposite for foldr. So, expanded, it looks like this: foldl (\acc element -> (read acc :: Int) + element) 0 ["10", "20", "30"] Since...

Sqoop Export with Missing Data

sql,postgresql,shell,hadoop,sqoop

I solved the problem by changing my reduce function so that if there were not the correct amount of fields to output a certain value and then I was able to use the --input-null-non-string with that value and it worked.

Calling find more than once on the same folder tree

linux,bash,shell,unix,find

Try this: find . -mmin +35 -or -mmin -25 find supports several logical operators (-and, -or, -not). See the OPERATORS section of the man pages for more details. ==================== EDIT: In response to the question about processing the two matches differently, I do not know of a way to do...

How do I align my output?

shell

I'd rewrite that as: #!/bin/bash while read -ra hello; do name=${hello[8]} if [[ $name == "$1"* ]]; then log=${hello[2]} echo "$log $name" fi done | column -t read -ra splits the input line and stores the words in the "hello" array. [[ $name == "$1"* ]] is a built-in way...

AWK count number of times a term appear with respect to other columns

linux,shell,command-line,awk,sed

Almost same as the other answer, but printing 0 instead of blank. AMD$ awk -F, 'NR>1{a[$2]+=$3;b[$2]++} END{for(i in a)print i, a[i], b[i]}' File pear 1 1 apple 2 3 orange 0 1 peach 0 1 Taking , as field seperator. For all lines except the first, update array a. i.e...

Implementing map on a tree using fold

scala,haskell

Try to write your last line as def map(tree:Tree[Int])(f:Int=>Int) : Tree[Int] = fold(tree , EmptyTree:Tree[Int])((l,x,r) => Node(f(x),l,r)) Scala's type inference is very limited compared to haskell, in this case it tries to infere type of fold from it's arguments left to right, and incorectly decides that result type of fold...

Keep track of loop without a counter

haskell

You can certainly do this without changing the type signature of func :: [Int] -> [Int]: have func call a different function, which takes an extra argument that is the counter you were talking about: func :: [Int] -> [Int] func = go 0 where go _ [] = []...

Redirect output from file to stdout

bash,shell,unix,stdout

Many tools interpret a - as stdin/stdout depending on the context of its usage. Though, this is not part of the shell and therefore depends on the program used. In your case the following could solve your problem: myprog -o - input_file ...