Bash提示替换文件中的字符串和变量?

Bash提示替换文件中的字符串和变量?,bash,Bash,因此,我正在研究如何组合一个Bash脚本,该脚本可以提示用户在文件中大量更改文件中的字符串和变量,并将更改应用于所有具有该字符串或变量的文件 举个例子,我有一堆文件,其中有一个带有数字值的字符串,我想把它改成一个新的值,即 font-size=30 假设我想把30换成一个不同的数值25。我知道这是可以做到的 find . -type f -exec sed -i 's/font-size=30/font-size=25/g' {} \; 但是如果我想让用户通过在bash提示符中自己输入值来更

因此,我正在研究如何组合一个Bash脚本,该脚本可以提示用户在文件中大量更改文件中的字符串和变量,并将更改应用于所有具有该字符串或变量的文件

举个例子,我有一堆文件,其中有一个带有数字值的字符串,我想把它改成一个新的值,即

font-size=30
假设我想把30换成一个不同的数值25。我知道这是可以做到的

find . -type f -exec sed -i 's/font-size=30/font-size=25/g' {} \;
但是如果我想让用户通过在bash提示符中自己输入值来更改为任何值是很棘手的,比如,ie

Search and replace all font values of %n
Font size Value = 30
Enter new value: 
作为一个要求用户输入的棘手提示,我如何才能做到这一点?因此,不仅能够搜索和替换属于Font size=的值的所有实例,还能够搜索和替换其他值,例如x和y位置值

基本上我想做的就是制作一个提示菜单,在这里你必须从菜单中选择你想做的事情,然后按照我上面描述的做。给它一个输入文件,或者一个包含一堆文件的目录,以下面的例子

Choose from menu [1-3]:

1 - Replace Font-size values
2 - Replace X and Y values
3 - Exit

- - -
Select file or directory target: <user_input_here>
您可以使用read创建交互式bash脚本。有关此实用程序的更多信息,请参阅相应的

看看下面的例子,你可以很容易地扩展到你的需要:

#!/bin/bash

function replace_fontsize {
  read -p "Old font-size: (Press Enter) " old_size
  read -p "New font-size: (Press Enter) " new_size
  read -p "Select file or directory target: (Press Enter) " path
  if [ -d "$path" ] ; then
    find "$path" -type f -exec sed -i 's/font-size=${old_size}/font-size=${new_size}/g' {} \;
  elif [ -f "$path" ] ; then
    sed -i 's/font-size=${old_size}/font-size=${new_size}/g' "$path"
  else
    echo "File/Directory ${path} doesn't exist"
    exit 1
  fi
}

function replace_x_and_y {
  # do whatever you want
  exit 0
}

echo "Choose from menu [1-3]:

1 - Replace Font-size values
2 - Replace X and Y values
3 - Exit"

read -n 1 -s menu

case $menu in
  1) replace_fontsize;;
  2) replace_x_and_y;;
  3) exit 0;;
esac

你的意思是互动而不是难以驾驭吗?根据《韦氏词典》的说法,不容易治理、管理或指挥。互动、难以驾驭,到底有什么区别?它们是两个完全不同的术语,含义完全不同。我能想到的唯一关系是它们都是英文单词。文件的格式是什么?如果所有文件都在同一个目录中或深度不超过2个,那么直接使用sed和文件globbing比使用find为每个文件生成一个单独的sed实例要高效得多,例如sed-I's/font size=30/font size=25/g'*。{布局、样式}
#!/usr/bin/env bash

# put any X here for X in the format X=<number>
options=("font-size" "x")

echo "Choose from menu [1-$((${#options[@]}+1))]"
index=1
for i in ${options[@]}; do
    echo -e "\t$((index++)) - $i"
done
echo -e "\t$((index)) - exit"

read -p 'select: ' sel                                                                                                                                
if ! [[ $sel =~ [1-9][0-9]* ]]; then
    echo "invalid selection. enter a number greater than 0"
    exit 1
fi
if [[ $sel -eq $index ]]; then
    echo "exiting.."
    exit 0
fi
echo "updating '${options[$((--sel))]}'"
read -p "enter the old value: " oval
read -p "enter the new value: " nval
echo "updating '${options[$sel]}=$oval' into '${options[$sel]}=$nval'"

# change the directory here if required and update the find query as needed
find . -type f -exec sed -i "s:${options[$sel]}=$oval:${options[$sel]}=$nval:g" {} \;