本文介绍了如何在bash编程中更新类似矩阵的数据(.txt)文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是bash编程的新手.我有这个文件,文件包含为:

  A B C D E1 X 0 X 0 02 0 X X 0 03 0 0 0 0 04 X X X X X 

其中X表示具有值,0表示其为空.

从那里,假设用户输入B3,它是0,这意味着我需要将其替换为X.什么是最好的方法?我需要不断更新此文件.

仅供参考:这是一个家庭作业问题,因此请不要给出直接的代码/答案.但是,非常感谢任何示例代码(如如何使用此功能等).

此致

新手Bash脚本编写器

如果我没记错的话,Bash可以直接调用/更新特定的列.行+列可以完成吗?

解决方案

如果可以使用 sed ,我将抛出这个花絮:

  sed -i"/^ 2/s/./X/4"/path/to/matrix_file 

输入

  A B C D E1 0 0 0 0 02 X 0 0 X 03 X X 0 0 X 

输出

  A B C D E1 0 0 0 0 02 X 0 X X 03 X X 0 0 X 

说明

^ 2 :这将sed限制为仅在以 2 开头的行(即第二行)上起作用.

s :这是替换命令

注意接下来的两个,"_"代表空白

._ :这是要匹配的模式..是匹配任何字符的正则表达式,因此 ._ 匹配任何字符后跟一个空格".请注意,如果可以确保只有两个字符可以是'0'和'X',则也可以是 [0X] _

X _ :这是替换文本.在这种情况下,我们将如上所述的任何字符后跟一个空格"替换为"X后跟一个空格"

4 :这与上面的模式文本的第4次匹配,即第4行包括行索引.

剩下要做的是使用变量代替 ^ 2 4 ,例如 ^ $ row $ col ,然后将字母A-E映射到1-5

I am new to bash programming. I have this file, the file contain is:

   A B C D E
 1 X 0 X 0 0
 2 0 X X 0 0
 3 0 0 0 0 0
 4 X X X X X

Where X means, it has value, 0 means its empty.

From there, let say user enter B3, which is a 0, means I will need to replace it to X. What is the best way to do it? I need to constantly update this file.

FYI: This is a homework question, thus please, dont give a direct code/answer. But any sample code like (how to use this function etc) will be very much appreciated).

Regards,

Newbie Bash Scripter

EDIT:

If I am not wrong, Bash can call/update directly the specific column. Can it be done with row+column?

解决方案

If you can use sed I'll throw out this tidbit:

sed -i "/^2/s/. /X /4" /path/to/matrix_file

Input

  A B C D E
1 0 0 0 0 0
2 X 0 0 X 0
3 X X 0 0 X

Output

  A B C D E
1 0 0 0 0 0
2 X 0 X X 0
3 X X 0 0 X

Explanation

^2: This restricts sed to only work on lines which begin with 2, i.e. the 2nd row

s: This is the replacement command

Note for the next two, '_' represents a white space

._: This is the pattern to match. The . is a regular expression that matches any character, thus ._ matches "any character followed by a space". Note that this could also be [0X]_ if you are guaranteed that the only two characters you can have are '0' and 'X'

X_: This is the replacement text. In this case we are replacing 'any character followed by a space' as described above with 'X followed by a space'

4: This matches the 4th occurrence of the pattern text above, i.e. the 4th row including the row index.

What would be left for you to do is use variables in the place of ^2 and 4 such as ^$row and $col and then map the letters A - E to 1 - 5

这篇关于如何在bash编程中更新类似矩阵的数据(.txt)文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 21:01