split a string in bash
Cut a string at a delimiter into parts or an array.
Steps
-
IFS=, read -r a b c <<< "x,y,z"three parts into three variables
-
IFS=, read -ra parts <<< "$line"every part into an array
-
echo "${parts[1]}"the second part (arrays start at 0)
-
cut -d, -f2 <<< "$line"only the second field, with cut
-
tr ',' '\n' <<< "$line"one part a line
Commands used
readcuttr
Each has a page in lore: lore read opens it.
Related recipes
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a file or folder existsTest in a script whether a path exists, is a file, a folder, empty or runnable.
- check if a string contains a textTest in a script whether a string contains, starts with or matches something.
- find the script's own folderInside a script, find the folder the script is in, to reach files next to it.