0

There's a string:

onetwothree.file.001.txt ; threefourfive.file.0.98.txt ; fivefoursix.file.14.txt

I want to split it by . and ; removing the prefix before the filename, so that it looks like this:

file.001.txt ; file.0.98.txt ; file.14.txt

Any ideas?

2

3 Answers 3

2
sed -e 's/[^.]*.//' -e 's/;[^.]*./; /g'

This initially removes the shortest substring up to . from the beginning and then can rely on ; to operate on the resulting string.

2

Taking the "in bash" literally, you could do something like this.

  • split the string into an array, delimited by semicolons

  • remove the prefix elementwise and store the result in a string, delimited by the first character of IFS

  • globally add back whitespace behind the delimiters

NOTE: you may wish to save the current IFS so you can restore it afterwards.

IFS=";"
read -a arr <<< "onetwothree.file.001.txt ; threefourfive.file.0.98.txt ; fivefoursix.file.14.txt"
printf -v str "${arr[*]#*.}"
printf "%s\n" "${str//;/; }"

ginving

file.001.txt ; file.0.98.txt ; file.14.txt
2

Or, with sed...

s="onetwothree.file.001.txt ; threefourfive.file.0.98.txt ; fivefoursix.file.14.txt"
sed -E "s/(^|; )[^\.]+\./\1/g" <<<$s

Walkthrough

(^|; )[^\.]+\.

Find any sub-element that either starts either at the beginning of the line ^ or | with ; (semicolon and a space) and which is followed by [^\.]+\. i.e. a continuous series which does not contain a literal . but which does end with a literal .

Then replace all of that with \1 which is the capture group (^|; )

Output

file.001.txt ; file.0.98.txt ; file.14.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.