getting the last field of a string separated by a particular delimiter in bash -
I am writing a script that uses a set of files to bash scripting in a directory. The file I am trying to copy may already be present in the directory, so I have to rename the file to avoid changing the original file
For example, if I were to "abc. Dd.java "and a file with the same name already exists, then I have to rename the file as" abc.dd1.java "and copy it.
If the destination is "abc.dd.java" and "abc.dd1.java" then the file name must be "abc.dd2.java"
I a code snippet Written by:
# $ is the absolute path to the original file in the file # $ path is the full path for the copied file in Copypath = "$ path" echo "$ Path "count = 1 while [-f" $ path "] part1 =` counterpart '$ copypath ". ("I (NF-1)))}} END {} "part2 =" countercurrent "$ copypath" | "$" "$ Count" "$ part1" count = 'expr "$" "{{FTS =" "} {printf ("% s ", $ NF)} END {}' path =" $ part1 "+ 1 It is very raw, but it is very raw. The file extension part and a better part of the name part can be better than the "copied CP" $ file "" $ path "
No way?
Thanks in advance
Answered a similar question
Here is a simple version (which mostly works), based on that link:
part1 = "$ {Copypath% *} Remove the file extension (at least. * Suffix) part2 = "$ {copypath ## *.}" # Delete the base path (longest * .fix) path = "$ {part1} $ {Count} . $ {Part2} "
And here is a complete answer that handles files without extensions:
If [[$ $ copypath" = ~ [ ^ /.] [.] [^ /.] + $]] Then # copy path has an extension in part1 = "$ {copypath%. *}" Part2 = ". $ {Copypath ## *.}" And # There is no valid extension, so at the end, insert number 1 = "$ copypoint" part2 = "" fi path = "$ {part1} $ {count} $ {part2}"
Features:
- Whitespace is handled well.
- Multiple points are handled as requested
likeabc.dd.java
becomesabc.dd1.java
- Handles files without any extensions E.g.
file
becomesfile1
- Dot files with any extension are also handled properly. E.g.
.bashrc
becomes.bashrc1
Alerts:
- Multiple Extensions Specially Controlled Are not there. For example
archive.tar.gz
becomesarchive.tar1.gz
instead ofarchive1.tar.gz
- If the first part extension ends with dot, this is not considered an extension. For example
this is a sentence ..
becomesthis is a sentence .. txt2
Regular expression for doing this as an extension Changes to[^ /] [.] [^ /.] + $
- Attempts to handle directories
- Tested in bash only, unlikely to work with other shells (but can be changed to use
grep
.
Comments
Post a Comment