Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

3 Answers 3

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
add comment
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
add comment

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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