使用bash shell脚本文件中的替换字符串 [英] Replacing a string in a file using bash shell script

查看:233
本文介绍了使用bash shell脚本文件中的替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个字符串的文件,做一些操作,放回字符串的文件中。下面给出的是什么,我需要的例子:

  $猫为sample.txt
TimeStamp-> 123456名称 - > ABC MAIL-GT&; abc@123.com
TimeStamp-> 23456名称 - > XYZ年龄> 25

让我修改我的问题。我想读后 TimeStamp-&GT这个字符串/号码; ,修改的基础上的要求相同,并且把它放回在同一个文件来获得或创建一个新的文件。比方说,操作乘以-1。

预期成果是:

  TimeStamp-> -123456名称 - > ABC MAIL-GT&; abc@123.com
TimeStamp-> -23456名称 - > XYZ年龄> 25


解决方案

下面一个纯粹的庆典解决方案:

 同时读取-ra线;做阅读#数组中的行的每一行
    ((行[1] * = - 1))#乘以-1第二元件(数)。
    回声$ {行[*]}#呼应修改行成newfile.txt
完成< sample.txt的> newfile.txt

说明

,而循环刚每行成的阵列

选项:


  

-r结果
      如果这个选项,则反斜杠不作为转义字符。反斜杠被认为是行的一部分。特别是,反斜杠换行符对可以不使用作为续行。


  
  

-a aname结果
      词语被分配给数组变量aname的循序索引,从0开始的所有元素从aname分配之前除去。其他名称参数被忽略。


,然后使用壳牌算术 * = )乘以数字(算术EX pression 的)和回声 ES修改行的 newfile.txt

I want to find a string in a file, do some operation and put back the string in the file. Given below is the example on what I need:

$ cat sample.txt
TimeStamp-> 123456 Name-> ABC Mail-> abc@123.com
TimeStamp-> 23456 Name-> XYZ Age-> 25

Let me modify my question. I want to read that string/number after TimeStamp->, modify the same based on the requirement and put it back to get in the same file or create a new file. Let's say the operation is multiply by -1.

Expected output is:

TimeStamp-> -123456 Name-> ABC Mail-> abc@123.com
TimeStamp-> -23456 Name-> XYZ Age-> 25

解决方案

Here a pure bash solution:

while read -ra line; do # read each line in the array "line"
    ((line[1]*=-1))     # multiply the second element (the number) by -1.
    echo "${line[*]}"   # echo the modified line into newfile.txt
done < sample.txt > newfile.txt

Explanation

The while loop just read each line into an array:

read options:

-r
If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.

-a aname
The words are assigned to sequential indices of the array variable aname, starting at 0. All elements are removed from aname before the assignment. Other name arguments are ignored.

and then uses Shell Arithmetic (*=) to multiply the number (an arithmetic expression) and echo'es the modified line to newfile.txt.

这篇关于使用bash shell脚本文件中的替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆