Bash One-Liners Explained, Part II: Working with strings - good coders code, great reuse |
| Bash One-Liners Explained, Part II: Working with strings Posted: 02 Jul 2012 07:13 AM PDT This is the second part of the Bash One-Liners Explained article series. In this part I'll show you how to do various string manipulations with bash. I'll use only the best bash practices, various bash idioms and tricks. I want to illustrate how to get various tasks done with just bash built-in commands and bash programming language constructs. See the first part of the series for introduction. After I'm done with the series I'll release an ebook (similar to my ebooks on awk, sed, and perl), and also bash1line.txt (similar to my perl1line.txt). Also see my other articles about working fast in bash from 2007 and 2008:
Let's start. Part II: Working With Strings1. Generate the alphabet from a-z $ echo {a..z} This one-liner uses brace expansion. Brace expansion is a mechanism for generating arbitrary strings. This one-liner uses a sequence expression of the form {x..y}, where x and y are single characters. The sequence expression expands to each character lexicographically between x and y, inclusive. If you run it, you get all the letters from a-z: $ echo {a..z} a b c d e f g h i j k l m n o p q r s t u v w x y z 2. Generate the alphabet from a-z without spaces between characters $ printf "%c" {a..z} This is an awesome bash trick that 99.99% bash users don't know about. If you supply a list of items to the In this one-liner the printf format is Here is the output if you run it: abcdefghijklmnopqrstuvwxyz This output is without a terminating newline because the format string was $ printf "%c" {a..z} $'\n'
Another way to add a trailing newline character is to echo the output of printf: $ echo $(printf "%c" {a..z}) This one-liner uses command substitution, which runs Want to output all letters in a column instead? Add a newline after each character! $ printf "%c\n" {a..z} Output: a b ... z Want to put the output from $ printf -v alphabet "%c" {a..z} This puts Similarly you can generate a list of numbers. Let's say from 1 to 100: $ echo {1..100} Output: 1 2 3 ... 100 Alternatively, if you forget this method, you can use the external $ seq 1 100 3. Pad numbers 0 to 9 with a leading zero $ printf "%02d " {0..9} Here we use the looping abilities of Output: 00 01 02 03 04 05 06 07 08 09 If you use bash 4, you can do the same with the new feature of brace expansion: $ echo {00..09} Older bashes don't have this feature. 4. Produce 30 English words $ echo {w,t,}h{e{n{,ce{,forth}},re{,in,fore,with{,al}}},ither,at} This is an abuse of brace expansion. Just look at what this produces: when whence whenceforth where wherein wherefore wherewith wherewithal whither what then thence thenceforth there therein therefore therewith therewithal thither that hen hence henceforth here herein herefore herewith herewithal hither hat Crazy awesome! Here is how it works - you can produce permutations of words/symbols with brace expansion. For example, if you do this, $ echo {a,b,c}{1,2,3} It will produce the result So this one-liner is just a smart combination of braces that when expanded produce all these English words! 5. Produce 10 copies of the same string $ echo foo{,,,,,,,,,,} This one-liner uses the brace expansion again. What happens here is foo foo foo foo foo foo foo foo foo foo foo 6. Join two strings $ echo "$x$y" This one-liner simply concatenates two variables together. If the variable Notice that x=-n y=" foo" echo $x$y Output: foo Versus the correct way: x=-n y=" foo" echo "$x$y" Output: -n foo If you need to put the two joined strings in a variable, you can omit the quotes: var=$x$y 7. Split a string on a given character Let's say you have a string $ IFS=- read -r x y z <<< "$str" Here we use the In this one-liner Also notice the use of You can also put the split fields and put them in an array: $ IFS=- read -ra parts <<< "foo-bar-baz" The 8. Process a string character by character $ while IFS= read -rn1 c; do # do something with $c done <<< "$str" Here we use the 9. Replace "foo" with "bar" in a string $ echo ${str/foo/bar} This one-liner uses parameter expansion of form To replace all occurrences of "foo" with "bar", use the $ echo ${str//foo/bar} 10. Check if a string matches a pattern $ if [[ $file = *.zip ]]; then # do something fi Here the one-liner does something if Here is another example that matches if answer is $ if [[ $answer = [Yy]* ]]; then # do something fi 11. Check if a string matches a regular expression $ if [[ $str =~ [0-9]+\.[0-9]+ ]]; then # do something fi This one-liner tests if the string 12. Find the length of the string $ echo ${#str} Here we use parameter expansion 13. Extract a substring from a string $ str="hello world" $ echo ${str:6} This one-liner extracts Here is another example: $ echo ${str:7:2} Output: or Enjoy!Enjoy the article and let me know in the comments what you think about it! If you think that I forgot some interesting bash one-liners related to string operations, let me know in to comments also! |
| You are subscribed to email updates from good coders code, great reuse To stop receiving these emails, you may unsubscribe now. | Email delivery powered by Google |
| Google Inc., 20 West Kinzie, Chicago IL USA 60610 | |
No comments:
Post a Comment
Keep a civil tongue.