Home > Mobile >  Splitting strings for appname and version
Splitting strings for appname and version

Time:12-24

I have a file with a couple of strings in it. Like :

appname-2021.12.24
appname2020-2021.12.23
app_name-2021.12.01
app_name2020-2021.12.02
app-name-2021.11.10

I want the appname and the version from these strings in single variables, so I can output an csv file from my script In this case :

appname,2021.12.24
appname2020,2021.12.23
app_name,2021.12.01
app_name2020,2021.12.02
app-name,2021.11.10

The version is always the substring with the dots in it, with a - before it.

My idea was to get the name and version in a separate variable, and ultimately merge it into a new variable with an extra comma

string = $appname","$appversion

I’ve tried to use cut with the - delimiter, but that doesn’t work with example 5. Using grep -Eo “[a-zA-Z_] ” doesn’t work either, missing the 2020 in example 2.

Would it be a possibility to find all songs and points from the end of the line to the first -?

CodePudding user response:

With bash:

while read -r line; do
  if [[ "$line" =~ (.*)-([^-] )$ ]]; then
    string="${BASH_REMATCH[1]},${BASH_REMATCH[2]}"
    echo "$string"
  fi
done < file

Output:

appname,2021.12.24
appname2020,2021.12.23
app_name,2021.12.01
app_name2020,2021.12.02
app-name,2021.11.10

See: The Stack Overflow Regular Expressions FAQ

CodePudding user response:

In plain bash:

#!/bin/bash

while read -r line; do
    printf '%s,%s\n' "${line%-*}" "${line##*-}"
done < file

Or, using a sed one-liner:

sed 's/\(.*\)-/\1,/' file
  • Related