Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a file with lines like:

0 6 973 1346 2318 456 431 93 58 1 1 0 0 0 0

I want to extract the 1st, 4th and 5th number and save them in variables in bash for further use. In the example above the values I want are '0', '1346' and '2318'.

I am thinking to use sed but I dont know how. Any other ways are also welcome.

ps. Thanks for the answer, following is what I am using now:

for fn in $(cat filelist); do
  more $fn | \                                                                                                                                                                         
      while read str; do
          echo $str
          var=$(echo $str | awk -F" " '{print $1,$2,$3,$4,$5}')
          set -- $var
          echo $1
          echo $4
          echo $5
  done
done

It works, yeah~~

share|improve this question
up vote 1 down vote accepted

cat myFile.txt | the script below:

#!/bin/bash
while read lineOfText
do
    echo $lineOfText | any of the approaches from http://www.unix.com/shell-programming-scripting/38450-split-string-using-separetor.html
done
share|improve this answer
    
but I want to read one line by line from a file, and parse the line. I dont have the string available – zhanwu Mar 9 '11 at 16:35
    
@zhanwu See the edited answer – AlcubierreDrive Mar 9 '11 at 16:55
    
The read lineOfText part take me some time to figure out, but finally it works. thx – zhanwu Mar 9 '11 at 17:12
while read -r fn
    while read -r first second third fourth fifth remainder
    do
        echo "$first"
        echo "$fourth"
        echo "$fifth"
    done < "$fn"
done < filelist
share|improve this answer

If I may offer a suggestion, you can simplify your script like this:

for fn in $(< filelist); do  #Replacement for $(cat filelist)
  while read str; do
    echo $str
    # No need for set --, unless you *really* want the values to be
    # placed in $1, $4, and $5
    read var1 var4 var5 <<< "$( echo $str | awk '{print $1,$4,$5}' )"
    echo $var1
    echo $var4
    echo $var5
  done < $fn  # Replaces more $fn |
done
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .