13.9.07

bash / split a line

I was searching on the web to find a method to split a line directly in bash... and I found some interesting information... it seems that bash has some string handling functions, an example:

#!/bin/bash
line="first test;second test"
VAL1=${line%;*}
VAL2=${line#*;}
echo $VAL1
echo $VAL2

The output would be:
first test
second test

Some explanation:
${variable%pattern}
Trim the shortest match from the end
${variable##pattern}
Trim the longest match from the beginning
${variable%%pattern}
Trim the longest match from the end
${variable#pattern}
Trim the shortest match from the beginning

Aucun commentaire: