1

I need help :) I have a file like this:

AA BC FG

RF TT GH

DD FF HH

(a few number of rows and three columns) and I want to put the letters of each column in a variable step by step in order to give them as input in another script. So I would like to obtain:

for the 1° loop:

var1 = AA
var2 = BC
var3 = FG

for the 2° loop:

var1 = RF
var2 = TT
var3 = GH

for the 3° loop:

var1 = DD
var2 = FF
var3 = HH
  • You should post generic programming questions in StackOverflow. – negusp Nov 8 '16 at 16:25
  • ops, I am sorry :( – pingu Nov 8 '16 at 16:33
  • Hmm I think this is possibly on topic, seems loosely like a text processing question @PatrickNegus – Zanna Nov 8 '16 at 17:18
  • 1
    @Zanna while that may be true, I don't know what language OP want to use; even more, its easier if collective programming questions/answers are posted in their correct sub-Exchange as it makes it easier for other people with similar issues to get answers. – negusp Nov 8 '16 at 17:35
  • 1
    while read -r var1 var2 var3; do <something with them>; done < file – steeldriver Nov 8 '16 at 17:40
3

If you file has exactly 3 whitespace-separated items on each line (no blank lines for example) then you should be able to use a simple while ... read loop:

while read -r var1 var2 var3; do
  ./otherscript "$var1" "$var2" "$var3"
done < "file"

If there are blank lines, then you should probably read complete lines and only parse the non-empty ones e.g.

while IFS= read -r line; do
  if [[ -n "$line" ]]; then 
    read -r var1 var2 var3 <<< "$line"
    ./otherscript "$var1" "$var2" "$var3"
  fi
done < "file"
  • read -r var1 ... on a blank line would leave $var1 empty which might be a more elegant way to test for blank lines. – David Foerster Nov 9 '16 at 0:41
0

Considering that your input file only provides arguments to script, the xargs is a reasonable choice in this situation. Lets take this script as example:

#!/bin/bash
echo "This is a test"
echo "var1 is $1 " "var 2 is $2 " "var 3 is $3"

We can use xargs with -L1 for taking 1 line in file as arguments, and --arg-file to specify the file containing those arguments. Thus:

$ xargs -L 1 -r --arg-file=input.txt ./somescript.sh 
This is a test
var1 is AA  var 2 is BC  var 3 is FG
This is a test
var1 is RF  var 2 is TT  var 3 is GH
This is a test
var1 is DD  var 2 is FF  var 3 is HH

Notice the -r option, which prevents xargs from running the script on blank lines, which are contained in your input file example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.