用于编辑 .ics 文件的 Bash 脚本

用于编辑 .ics 文件的 Bash 脚本

我想创建一个 bash 脚本,从文件夹中的 .ics 文件中进行选择,然后在选定的文件中执行“查找和替换”,然后保存并重命名该文件。我从搜索中拼凑了一些内容,但不太清楚自己在做什么才能让它们全部发挥作用……

以下是我的菜单:

    #!/bin/bash

echo "The following `*.ics` files were found; select one:"

# set the prompt used by select, replacing "#?"
PS3="Use number to select a file or 'stop' to cancel: "

# allow the user to choose a file
select filename in *.ics
do
# leave the loop if the user says 'stop'
if [[ "$REPLY" == stop ]]; then break; fi

# complain if no file was selected, and loop to ask again
if [[ "$filename" == "" ]]
then
    echo "'$REPLY' is not a valid number"
    continue
fi

# now we can use the selected file
echo "$filename installed"

# it'll ask for another unless we leave the loop
break
done

这是我目前用来编辑 .ics 文件的代码,但它会更改当前目录中的所有 .ics 文件:

#!/bin/bash

###Fixes all .ics files to give ALL DAY events rather than 0000-2359  
####All .ics files
FILES="*.ics"


# for loop read each file
for f in $FILES
do
INF="$f"

##Change DTSTART:[yyyymmddThhmmss] to DTSTART;VALUE=DATE...##

sed -i[org] 's/DTSTART:2016/DTSTART;VALUE=DATE:2016/g' $INF

sed -i[org] 's/T[0-9][0-9][0-9][0-9][0-9][0-9]/ /g' $INF

###Remove DTEND:###
sed -i[org] 's/DTEND:[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/ /g'$INF

done

我怎样才能将这一切结合起来以实现我的目标?

答案1

您也许可以使用case构造来构造它,如下所示:

#!/bin/bash

shopt -s nullglob

echo 'The following `*.ics` files were found; select one:'

select f in *.ics "Quit"; do
  case $f in
    "Quit")
      echo "Quitting"
      break
      ;;
    *)
      if [ -z "$f" ]; then
        echo "Invalid menu selection"
      else
        echo "Doing something with $f"
      fi
      ;;
    esac
done

更改echo "Doing something with $f"以对所选文件执行任何操作 - 如果它相对复杂,我建议将其移动到 shell 函数。记得引用 ie"$f"以防止分词。

答案2

好的,我明白了。这是我的代码:

#!/bin/bash


shopt -s nullglob

echo 'The following `*.ics` files were found; select one:'

select f in *.ics "Quit"; do
  case $f in
    "Quit")
      echo "Quitting"
      break
      ;;
    *)
      if [ -z "$f" ]; then
        echo "Invalid menu selection"
      else
        echo "Creating all-day events in $f"
          ##Change DTSTART:[yyyymmddThhmmss] to DTSTART;VALUE=DATE...##
          sed -i.orig 's/DTSTART:2016/DTSTART;VALUE=DATE:2016/g' "$f"
          sed -i.orig 's/T[0-9][0-9][0-9][0-9][0-9][0-9]/ /g' "$f"
          ###Remove DTEND:###
          sed -i.orig  's/DTEND:[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/ /g' "$f"
      fi
      ;;
    esac
done

有没有办法在有效或无效响应后重复菜单?(抱歉,我对这个 bash 东西还不太熟悉,正在努力边学边做。)

相关内容