1

I'm trying to assign a variable using another variable that is being read in from a while and also being parsed at the same time. However, for some reason I'm not able to get the new variable to get the data i want. Any help would be appreciated.

while read line
do
    foldername=$($line | awk -F'/' '{ print $4 }')
    echo $foldername
done < folderlist.txt

folderlist.txt contains a list of directory where i'm trying to read the 4th parameter.

2
  • 2
    $line | awk -F'/' '{ print $4 }' alone is wrong. You should echo "$line" | awk -F'/' '{ print $4 }' or awk -F'/' '{ print $4 }' <<< "$line". Also, if you are getting the filename you can consider using basename $line. Commented May 27, 2014 at 15:56
  • 1
    Thanks for the quick reply! That works. I just did foldername=$(echo "$line" | awk -F'/' '{ print $4 }') Commented May 27, 2014 at 16:04

1 Answer 1

1

why not: awk '{ print $4 }' folderlist.txt ? The problem in your script fragment above may be that you're executing contents of $line as command, rather than merely parsing it, where you do $( $line ... | awk ... )

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This works also. foldername=$(awk -F'/' '{ print $4 }' <<< "$line"). what i'm trying to do is get the 4th parameter..then create a new folder under a new directory using that 4th parameter.
ah, ok. then don't read whole line into one variable, but fields 1, 2, 3, 4, and rest into vars, from which you pick the var containing field 4: while read f1 f2 f3 f4 rest; do echo "yourcommands $f4"; done < folderlist.txt - no subshelling involved. changing field delimiter is done by assigning to variable IFS
foo="a/b/c/d"; IFS="/"; while read f1 f2 f3 f4; do echo $f3; done <<< "$foo" gives an idea how to use that. - this 5 minute limit on editing comments makes testing on the go a bit hard, sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.