0

I've got a file CATALOG.dat containing lines like the following:

event_017_3916.gz

I need to extract the first number of this line (017). This number is necessary to launch another program (PROGRAM.C), which requires input numbers to start (i.e., it should be used like $ PROGRAM.C 017). Actually, I just need to build up a command like:

PROGRAM.C 017

inside my shell script. My problem is: how do I read the 017 and set it as a variable that I can use to build up the command? Thanks a lot for you help!

urgeo
  • 645
  • 1
  • 9
  • 19
  • You should include the command you have chosen from the answers to [your previous question](http://stackoverflow.com/questions/26591016/reading-numbers-from-a-text-line-in-bash-shell) here so that people realize that you are asking about the "store in a variable and use later" part and not the "get the numbers" part of this question. – Etan Reisner Oct 27 '14 at 18:16
  • possible duplicate of [Store output from sed into a variable](http://stackoverflow.com/questions/6749128/store-output-from-sed-into-a-variable) – Etan Reisner Oct 27 '14 at 18:17

3 Answers3

0

An awk solution:

awk -F_ '{print $2}' file

Sets the delimiter to _ (-F_) and prints the second (print $2) field (where 017 is stored)

To run trough the file and save it into a variable ($line contains 017):

while read line
do
  echo " > $line"
  PROGRAM.C $line
done < <(awk -F_ '{print $2}' file)

Additionally you can use xargs to execute the command with:

awk -F_ '{print $2}' file | xargs PROGRAM.C

That executes PROGRAM.C xyz for every line in the file, where xzy is the extracted digit.

chaos
  • 8,162
  • 3
  • 33
  • 40
  • 1
    As you are using [my answer to the previous question](http://stackoverflow.com/a/26591085/2088135), it would be nice to see some attribution. – Tom Fenech Oct 27 '14 at 18:29
  • @TomFenech I didn't copy anything, that's a concurrence. But anyway have a +1^^ – chaos Oct 27 '14 at 18:34
0

My solution:

awk -F "_" '{print $2}' | xargs -n1 PROGRAM.C
Vytenis Bivainis
  • 2,308
  • 21
  • 28
0
while IFS=_ read event first_num rest ; do
    echo "PROGRAM.C $first_num"
done <CATALOG.dat
pjh
  • 6,388
  • 2
  • 16
  • 17
  • 1
    It may be beneficial to explain how or why this code works for the audience in general. – Compass Oct 27 '14 at 19:15
  • 1
    In reply to the suggestion from @Compass to explain why the code works, I refer to the documentation for the 'read' function on the Bash manual page. The first few sentences cover everythng needed to understand the code in the answer, and I couldn't explain it any better. – pjh Oct 28 '14 at 17:56
  • There's no problem with your answer. It's just that some will be marked for review as "possibly low quality" in Stack Overflow's Review, due to lack of length or content, and since I don't know bash, I can only base it off of what you have provided :) No penalties, just a friendly reminder! – Compass Oct 28 '14 at 18:00