0

I have a file (x.txt) with a single column containing a hundred values.

228.71
245.58
253.71
482.72
616.73
756.74
834.72
858.62
934.61
944.60        
....

I want to input each of these values to an existing script I have such that my command on the terminal is:

script_name 228.71 245.58 253.71........... and so on.

I am trying to create a bash script such that each row is read automatically from the file and taken into the script. I have been trying this for a while now but could not get a solution.

Is there a way to do this?

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • please update the question with your coding attempts and the (wrong) output generated by your code – markp-fuso Oct 26 '22 at 22:24
  • are you looking to store each value from the .txt file inside a list? – logan_9997 Oct 26 '22 at 22:24
  • 2
    please confirm the structure of your input file ... one line with 100 values *or* 100 lines with one value per line? – markp-fuso Oct 26 '22 at 22:27
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 26 '22 at 22:44
  • [This](https://stackoverflow.com/questions/15580144/how-to-concatenate-multiple-lines-of-output-to-one-line) could be of use – bn_ln Oct 26 '22 at 23:05

4 Answers4

0

You could read the text file line by line into a list, stripping any newlines on the way. The subprocess.call call takes a list of the command to run plus any arguments. So create a new list with the values just read and the name of the command.

import sys
import subprocess

values = [line.strip() for line in open("x.txt")]
subprocess.call(["script_name"] + values)
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

In pure Bash, you could use mapfile/readarray to have an array populated with each line of input file.

For example:

#!/usr/bin/env bash
CMDNAME="${0##*/}"
mapfile -t data < x.txt
printf "%s %s\n" "$CMDNAME" "${data[*]}"

Output with script named foo.sh :

$ ./foo.sh
foo.sh 228.71 245.58 253.71 482.72 616.73 756.74 834.72 858.62 934.61 944.60
Bruno
  • 580
  • 5
  • 14
0

There's a standard utility for this.

$ cat x.txt | xargs script_name

Consult the man page for details. Possibly you'd like to adjust the -n value.

J_H
  • 17,926
  • 4
  • 24
  • 44
0

Using awk, you can concatenate them to a single line by making ORS=" "

awk 'BEGIN {ORS=" "} { print } ' x.txt

Copy the output to a variable and pass it to the script_name

stack0114106
  • 8,534
  • 3
  • 13
  • 38