#Linux : extract substring in #Bash
One of the most important tasks in dealing with data is string manipulation. We already saw how to use awk and grep to efficiently sift through text files using command line tools instead of developing ad-hoc code. To step it up a notch, we can also do some heavier preprocessing of the data, such as selecting only the subset of information that matches a particular pattern, to ensure data coming out of our pipeline is of good quality.
In this case, we use a Bash feature called parameter expansion. Let’s assume we have the text data in a variable
TEXT_LINE and an expression
pattern to match (in file-name matching format), this is a summary of the possible expansion:
- Delete shortest match of pattern from the beginning
- Delete longest match of pattern from the beginning
- Delete shortest match of pattern from the end
- Delete longest match of pattern from the end
- Get substrings based on position using numbers
- Replace particular strings or patterns
So for example, to extract only the file name without the extension:
or to extract user name from an email:
or extract the file name from an absolute path:
NOTE: You can’t combine two operations, instead you have to assign to an intermediate variable.
Posted on February 11, 2019, in Linux and tagged command line tools, Data Processing, linux, script bash. Bookmark the permalink. Leave a comment.
Leave a comment