【问题标题】:How to make multiple search and replace in files via bash如何通过bash在文件中进行多次搜索和替换
【发布时间】:2017-11-03 21:46:12
【问题描述】:

我有脚本。在这个脚本中,我搜索和替换了单词。一个字一个字,直到单词“结束”。没关系,它有效。你可以看到我的脚本正文:

#!/bin/bash

end=end   
until [ "$first" = "$end" ];do
    echo "please write first word";    
    read first   
    if grep -q "$first" *txt; then
        echo "word is exists"
        grep "$first" *txt
        echo "please write second word";    
        read second
        sed -i 's/'"$first"'/'"$second"'/g' *txt
    else
        echo "second word does not exists"
        exit 1
    fi
done

它对我有用。我在结果控制台中,我可以无休止地循环单词,但是如果我想做这样的事情:我怎样才能在一行中写多个单词。

例如:“狗”“猫”“鱼”

然后搜索并替换所有这些词。怎么办?例如,如果我需要替换这些单词(“elephat”“mouse”“bird”)。你怎么能这样做? 我的意思是搜索和替换单词,比如参数。

【问题讨论】:

  • 您的意思是接收要替换的单词作为参数?或者从文件中读取它们?
  • 你必须学会​​缩进。我要编辑。看在上帝的份上,以可读的方式编写代码。
  • 我的意思是接受参数之类的词

标签: bash for-loop search replace while-loop


【解决方案1】:

您只需要一个循环来处理参数。

假设您运行脚本并传递成对的原始替换词 (myscript.sh original_word1 replacement1 original_word2 replacement2 ...),它将类似于以下内容:

while [[ $# -gt 1 ]]
do
  original="$1"
  replacement="$2"

  # your code for actually replacing $original with $replacement

  shift   # discard already processed original arg
  shift   # discard already processed replacement arg
done

请注意,如果用户在没有替换的情况下传递了最后一个原始单词,脚本将忽略它

【讨论】:

    【解决方案2】:

    你的英语很粗糙,但我想你希望能够提示输入多个单词,并用新的集合替换它们?

    下面的代码将让您运行类似replace_words one two three 的程序,然后提示您输入要替换的单词列表,例如1 2 3。之后,它就退出了。

    declare -a replace_list=( "$@" )    # get the replace list as passed arguments
    echo -n "Enter words to replace with: ";        read -ra sub_list
    for ((i=0; i < "${#replace_list[@]}"; ++i)); do
        if grep -q "${replace_list[$i]}" *txt; then
            echo "first word is exists"
            sed -i "s/${replace_list[$i]}/${sub_list[$i]}/g" *txt
        else
            echo "${replace_list[$i]} does not exists"
            exit 1
        fi
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2022-11-28
      • 2021-10-19
      • 1970-01-01
      • 2017-11-13
      • 2015-06-29
      • 1970-01-01
      相关资源
      最近更新 更多