Parsing Text with a read Statement

Problem

The are many ways to parse text with bash. What if I don’t want to use a function? Is there another way?

Solution

Use the read statement.

#!/usr/bin/env bash
# cookbook filename: parseViaRead
#
# parse ls -l with a read statement
# an example of output from ls -l follows:
# -rw-r--r--  1 albing users 126 2006-10-10 22:50 fnsize

ls -l "$1" | { read PERMS LCOUNT OWNER GROUP SIZE CRDATE CRTIME FILE ;
                 echo $FILE has $LCOUNT 'link(s)' and is $SIZE bytes long. ;
             }

Discussion

Here we let read do all the parsing. It will break apart the input into words, where words are separated by whitespace, and assign each word to the variables named on the read command. Actually, you can even change the separator, by setting the bash variable $IFS (which means Internal Field Separator) to whatever character you want for parsing; just remember to set it back!

As you can see from the sample output of ls -l, we have tried to choose names that get at the meaning of each word in that output. Since FILE is the last word, any extra fields will also be part of that variable. That way if the name has whitespace in it like “Beethoven Fifth Symphony” then all three words will end up in $FILE.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.