Добавить 'дубликат файла' к контекстному меню панели файлового браузера Gedit?

В TextMate и другой IDE как Netbeans, существует опция щелчка правой кнопкой копировать файл. Действительно ли возможно добавить эту опцию в панели файлового браузера Gedit при щелчке правой кнопкой?

В настоящее время я могу создать новые файлы, папки, удалить существующий, переименовать, даже 'открывают терминал здесь'. Каким образом у нас нет опции 'дубликата файла'?


От использования инструментов External я придумал этот сценарий:

Примечание: Я не так большая часть программиста Python :-)

#!/bin/sh

DocDir=$GEDIT_CURRENT_DOCUMENT_DIR #document directory
DocNm=$GEDIT_CURRENT_DOCUMENT_NAME #document name

NNM=$DocNm'_copy' #append _copy to document name
cp "$DocRir/$DocNm" "$DocDir/$NNM" #duplicate

До сих пор это копирует файл хорошо, хотя существуют некоторые проблемы, с которыми я встретился:

  1. index.php переименовывается к index.php_copy => это должно быть index_copy.php
  2. init.jquery.js должен быть init_copy.jquery.js

Предпочтительное решение состояло бы в том, чтобы извлечь первую часть названия документа, добавить '_copy' и затем присоединиться к нему с последней частью имени (exension).

Можно ли улучшить сценарий или даже создать ли лучший?

3
задан 14 May 2014 в 14:55

1 ответ

Вот решение, которое должно работать с плагин ExternalTools рекомендуемый @Rinzwind:

#!/bin/bash

FILE="$GEDIT_CURRENT_DOCUMENT_PATH"

FILENAME="${FILE##*/}"
EXTENSION_PRE="${FILENAME#*.}"
BASENAME="${FILENAME%%.*}"
DIRNAME="${FILE%/*}"

if [[ "$FILENAME" = "$EXTENSION_PRE" ]] # handle files without extension
  then
      EXTENSION=""
  else
      EXTENSION=".$EXTENSION_PRE"
fi

cp -v "$FILE" "$DIRNAME/${BASENAME}_copy$EXTENSION"

я протестировал его на файлы без расширения (например, Untitled Document) с единственным расширением (например, Untitled Document.txt) и составными расширениями (например, Untitled Document.text.txt).

Вот то, как я настроил его с внешними инструментами gEdit (эта установка покажет (подробный) вывод CP в нижней области):

enter image description here

<час>

Редактирование

Вот является постепенным объяснением того, что делает код:

#!/bin/bash
#  Note: we are using /bin/bash and not /bin/sh
#  /bin/sh is the DASH shell, /bin/bash the BASH shell
#
#  We need BASH to perform the string manipulations on
#  the file path.
#
#  More information on the differences may be found here:
#  - http://stackoverflow.com/a/8960728/1708932
#  - https://wiki.ubuntu.com/DashAsBinSh

FILE="$GEDIT_CURRENT_DOCUMENT_PATH" # assign the full file path provided
                                    # by gedit to a shorter variable

# What follows are a number of bash string manipulations.
# These are very well documented in the following article:
# - http://linuxgazette.net/issue18/bash.html

# 1.) remove everything preceding (and including) the last slash
#     in the file path  to get the file name with its extension
#     (e.g. /home/test/file.tar.gz → file.tar.gz)
FILENAME="${FILE##*/}"

# 2.) remove everything in the file name before (and including)
#     the first dot to get the extension
#     (e.g. file.tar.gz → tar.gz)
EXTENSION_PRE="${FILENAME#*.}"

# 3.) remove everything in the file name after (and including) 
#     the first dot to get the basename
#     (e.g. file.tar.gz → file)
BASENAME="${FILENAME%%.*}"

# 4.) remove everything after (and including) the last slash
#     in the file pathto get the directory path
#     (e.g. /home/test/file.tar.gz → /home/test)
DIRNAME="${FILE%/*}"


# If there's no extension in the filename the second string manipulation
# will simply print the filename. That's why we check if $FILENAME and
# $EXTENSION_PRE are identical and only assign EXTENSION to a value if
# they aren't.

if [[ "$FILENAME" = "$EXTENSION_PRE" ]]
  then
      EXTENSION=""
  else
      EXTENSION=".$EXTENSION_PRE"
fi

# in the last step we compose the new filename based on the string 
# manipulation we did before and pass it to cp
cp - v "$FILE" "$DIRNAME/${BASENAME}_copy$EXTENSION"
3
ответ дан 17 November 2019 в 20:51

Другие вопросы по тегам:

Похожие вопросы: